* Reply to a message in personal_mail.
David Van Hoose wrote in a message to Tom Torfs:
RA> char name[40];
RA> gets(name);
DVH> If you do that verbatim, you will have an overflow problem with
DVH> all known compilers.
There's no way a compiler can fix this and remain ISO-compliant (at least in
C but I suspect the C++ standard copied this) as gets() has to read
characters until an EOF or newline is encountered.
DVH> char name[40];
DVH> gets(name);
DVH> name[40]='\n';
DVH> You have to put a NULL on the end or it will have an overflow
DVH> problem. I believe you have to do that with 'fgets' as well..
DVH> Just put the null character on the very end of the array.
First of all '\n' is not a NUL character (BTW, NULL should be used to refer
to a pointer, although I'm aware that in C++ you can get away with it), you
should use '\0' or plain 0.
But most important of all: your code itself overflows the array --- it can
store only elements 0 through 39 and you try to store a character in element
40.
Besides, AFAIK fgets() is required to add a NUL character (unlike e.g.
strncpy), it just may or may not have a trailing newline.
greetings,
Tom
tomtorfs@village.uunet.be
--- timEd/2 1.10+
---------------
* Origin: 80X86 BBS 32-15-24.62.32 V.34/V.FC (24h/24h) (2:292/516)
|