C programming gets stdio.h


In C programming the <stdio.h> gets function read characters from the input stream ‘stdin’ until end-of-file is encountered or a new line is read.The declaration of the function is shown below.

char *gets(char *s);

Parameters:
s -An array to which the entered characters is stored.

Return type
char* -Returns ‘s’ if successful.If end-of-file is encountered and no characters have been read into the array,the contents of the array remain unchanged and a null pointer is returned.If a read error occurs during the operation,the array contents are indeterminate and a null pointer is returned.

Note the new line character that is entered is discarded and a null character is written immediately after the
last character read into the array.This function is same with ‘fgets’,but ‘fgets’ being more secure.

Link : C fgets stdio.h

Code example

char s[20] , *c ;

c=gets(s);

printf(“s=%s \nc=%s” , s , c);

Output in Code::blocks,

New string
s=New string
c=New string

The output is obvious and there is nothing much to explain here.Below a detail explanation of why you should prefer ‘fgets’ over ‘gets’ is given.





Why fgets is more secure than gets

The fgets function can also read characters from the input stream by passing the third argument as ‘stdin’,for more information on ‘fgets’ visit the link C fgets stdio.h.The advantage of using ‘fgets’ is the number of characters to be stored in an array is determined by the second argument.In other words the number of characters to be read is fixed.However,in ‘gets’ function there is every chance of storing the characters past the end of the array size which can be a potential threat for an unexpected behavior or a bug in your program.Consider the program below.

Code example

char s[20] ;

printf(“Enter any string\n”);
gets(s);

printf(“\ns=%s” , s );

Output in Code::blocks,

Enter any string
Corecplusplustutorial.com is the best
s=Corecplusplustutorial.com is the best

The string “Corecplusplustutorial.com is the best” has 37 characters which is way beyond the allocated array size.But you can see that the output is still “Corecplusplustutorial.com is the best” which utterly conflict with the array size because ‘s’ can store only 20 characters.No doubt,this is an error.

If you use ‘fgets’ we can fix the number of characters stored in ‘s’ array.Consider the program below.

Code example

char s[20] ;

printf(“Enter any string\n”);
fgets(s , sizeof(s) , stdin );

printf(“\ns=%s” , s );

Output in Code::blocks,

Enter any string
Corecplusplustutorial.com is the best
s=Corecplusplustutori

The number of characters in ‘s’ array is 19 but note there is a NULL character at the end so including with NULL character the number of characters is 20.With ‘fgets’ the chance of reading characters beyond the allocated size is avoided.


Related links

->C fgetc stdio.h