void gctinp (char *inp, int siz)
{
puts ("Input value: ");
fgets (inp, siz, stdin);
printf ("buffer3 getinp read %s", inp);
}
From what I've read, fgets is supposed to be used when you want to limit the size of input. So this code shouldn't be vulnerable right?
It is being called like so:
int main (int argc, char *argv[])
{
char buf[16];
getinp (buf, sizeof (buf));
display (buf);
printf ("buffer3 done\n");
}
Thanks for your time.
You won't strike buffer overflow problems if you enter more characters than can be safely stored since
fgets
restricts the input. It also adds a null terminator (assuming buffer size is greater than 0, of course).However, you will have problems with information being left in the input buffer the next time you try to read something - this is something that users will find very annoying, entering something like
hello again
and having it treated as two separate inputs likehello ag
andain
. And there's no indication given byfgets
that it stopped retrieving input before the end of the line so, as far as your code is aware, everything is fine.The major things you need to look out for (re buffer overflows on input) are, at a minimum,
scanf
with an unbounded%s
format string andgets
, which has no limiting size argument, neither of which are in your code.If you're looking for a more robust input solution with size limiting, prompting and buffer clearing, check out this code, which provides all those features:
And, doing some basic tests:
No, it isn't prone to stack overflow.
Are you confusing stack overflow and buffer overflow by any chance?
http://en.wikipedia.org/wiki/Stack_overflow
fgets will read at most one less than the specified number of bytes, and will make sure that the read string is null-terminated. So as long as you pass the correct size, it should be fine (although the string might not end in a newline).