我在C中调用一个外部方法时遇到了一个有趣的问题,该方法尝试strtok通过引用传递给它的本地(主)字符串.如果我在main中strtok字符串,它按预期工作,但如果我调用外部方法,它会失败并出现segfault.Valgrind在访问strtok结果的第一个元素时的输出:
Address 0xfffffffffeffebc0 is not stack'd, malloc'd or (recently) free'd
Run Code Online (Sandbox Code Playgroud)
--- 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);
}
Run Code Online (Sandbox Code Playgroud)
--- test2.c ---
void tt(char* l) {
char* x = strtok(l, " \t");
printf("%p\n", x);
printf("%c\n", x[0]);
}
Run Code Online (Sandbox Code Playgroud)
编译
gcc -c test2.c -o test2.o …Run Code Online (Sandbox Code Playgroud)