c - My strlen code segfaults -
can tell m why getting sigsegv on this?
#include <stdio.h> #include <string.h> int main () { char szinput[256]; printf ("enter sentence: "); fgets (szinput, 256, stdin); size_t n = (unsigned)strlen(szinput); printf ("the sentence entered %ld characters long.\n", n); return 0; }
when run segfaults.
unix>strlen_ex enter sentence: foo bar burr segmentation fault
i can see no reason crash is, there potential...
it best pass sizeof szinput
instead of explicit 256. prevents accidentally getting wrong size in fgets
.
char szinput[256]; printf ("enter sentence: "); fgets (szinput, sizeof szinput, stdin);
for example if set array 8 bytes, leave fgets
call @ 256 , enter "hello world":
char szinput[8]; printf ("enter sentence: "); fgets (szinput, 256, stdin);
then fgets call write beyond end of szinput
. on stack potentially overwrite important (such fgets
stack frame). segfault (or fail anyway).
Comments
Post a Comment