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
fgetsrestricts 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 againand having it treated as two separate inputs likehello agandain. And there’s no indication given byfgetsthat 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,
scanfwith an unbounded%sformat 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: