S
Sathyaish
I noticed that gets() reads into the buffer even if the you've not
allocated enough memory. For instance, if you do:
This works without a problem even though I initialized the buffer with
a single char only for the heck of it. Of course, not initializing the
char pointer at all will definitely result in a crash. For instance,
doing just this definitely would result in a null-pointer exception
and would crash the program.
So, my question is whether with gets(), unlike most other C functions
where we the programmers are supposed to make good guesses as to the
amount of memory we need, can we just get away without caring about
the length of the buffer required?
If I explicity say,
I explcitiy define the length of the buffer I would be using, but
gets() keeps returning input even if it exceeds the 999 characters I
expected.
The documentation here
http://www.cplusplus.com/ref/cstdio/gets.html
says:
Please shed some light on this function's behaviour as regards buffer
allocation.
allocated enough memory. For instance, if you do:
Code:
char *str=(char*)malloc(sizeof(char));
printf("Enter something about yourself below:\n\n");
gets(str);
printf("\n\n");
puts(str);
This works without a problem even though I initialized the buffer with
a single char only for the heck of it. Of course, not initializing the
char pointer at all will definitely result in a crash. For instance,
doing just this definitely would result in a null-pointer exception
and would crash the program.
Code:
char *str
printf("Enter something about yourself below:\n\n");
gets(str);
printf("\n\n");
puts(str);
So, my question is whether with gets(), unlike most other C functions
where we the programmers are supposed to make good guesses as to the
amount of memory we need, can we just get away without caring about
the length of the buffer required?
If I explicity say,
Code:
char str[1000];
printf("Enter something about yourself below:\n\n");
gets(str);
printf("\n\n");
puts(str);
I explcitiy define the length of the buffer I would be using, but
gets() keeps returning input even if it exceeds the 999 characters I
expected.
The documentation here
http://www.cplusplus.com/ref/cstdio/gets.html
says:
There is no limit on how many characters gets may read, so it's your
job to determinate the length of the buffer you will need.
Please shed some light on this function's behaviour as regards buffer
allocation.