strtok on a local variable in C -
i encountered interesting problem in c, when calling external method main tries strtok local (main) string passed reference. if strtok string in main, works expected, if call external method, fails segfault. valgrind's output on accessing first element of strtok result:
address 0xfffffffffeffebc0 not stack'd, malloc'd or (recently) free'd
--- test.c ---
extern void tt(char* x); main(argc, argv) int argc; char *argv[]; { char line[5000]; // if uncomment following 2 lines , comment above works expected // char * line; // line = malloc(5000); strcpy(line, "hello world"); printf("%d\n", sizeof(line)); tt(line); }
--- test2.c ---
void tt(char* l) { char* x = strtok(l, " \t"); printf("%p\n", x); printf("%c\n", x[0]); }
compile by
gcc -c test2.c -o test2.o gcc test.c test2.o
imho should print out like:
./a.out 0x..... h
but instead segfault on printing "h".
can please explain behavior?
thanks.
in file
--- test2.c ---
void tt(char* l) { char* x = strtok(l, " \t"); printf("%p\n", x); printf("%c\n", x[0]); }
you haven't included string.h
, compiler assumes return type of int
strtok
. line
char *x = strtok(l, " \t");
doesn't assign proper pointer x
(as valgrind output shows, pointers 64 bits @ least, int
32 bits). dereferencing corrupted pointer causes segmentation fault.
Comments
Post a Comment