Here is a version of the code:
Code:
#include<stdio.h>
int main()
{
char str[10];
int size = 10;
gets(str);
printf("message: '%s'. Size: %d\n",str,size);
return 0;
}
I can compile it as follows:
Code:
$ gcc test.c
/tmp/ccgy3XXc.o: In function `main':
test.c:(.text+0x19): warning: the `gets' function is dangerous and should not be used.
And then run it...
Code:
$ ./a.out
Hello
message: 'Hello'. Size: 10
$ ./a.out
Hello World
message: 'Hello World'. Size: 100
Notice how when I run it a second time the size changes from 10 to 100. This is (as many others have said) because gets doesn't limit the size of the input. I have entered more than the 10 characters that str can hold and so the data overflows into (in this case) the next variable which just happens to be size.
Which I hope explains the warning message.
So if gets() is out what should be used? Again as already mentioned fgets() fills the role in a safer way.
Code:
#include<stdio.h>
int main()
{
char str[10];
int size = 10;
fgets(str,size,stdin);
printf("message: '%s'. Size: %d\n",str,size);
return 0;
}
compile thusly:
and no warnings looking good...
Code:
$ ./a.out
Hello
message: 'Hello
'. Size: 10
$ ./a.out
Hello World
message: 'Hello Wor'. Size: 10
The good news is that no more than size -1 characters are read in and so the memory is not being stomped all over. The not so wonderful news is that the new line character is retained if it was reached and I don't know if I have reached the end of the input.
These limitations can be addressed by using the strlen() function and then looking for the newline character.
Left as an exercise