I encountered an interesting problem in C, when calling an external method from main that tries to strtok a local (main) string that is passed to it by reference. If I strtok the string in main, it works as expected, but if I call the external method, it fails with segfault. Valgrind's output on accessing the first element of the strtok result:
Address 0xfffffffffeffebc0 is 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 I uncomment the following two lines and comment above it works as 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 it should print out something like:
./a.out
0x.....
h
But instead I get segfault on printing the "h".
Can somebody please explain this behavior?
Thanks.