参照によって渡されるローカル (メイン) 文字列を strtok しようとする main から外部メソッドを呼び出すときに、C で興味深い問題が発生しました。main で文字列を strtok すると期待どおりに動作しますが、外部メソッドを呼び出すと segfault で失敗します。strtok 結果の最初の要素にアクセスしたときの Valgrind の出力:
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]);
}
によってコンパイル
gcc -c test2.c -o test2.o
gcc test.c test2.o
私見は、次のようなものを出力する必要があります。
./a.out
0x.....
h
しかし、代わりに、「h」を印刷するとセグメンテーション違反が発生します。
誰かがこの動作を説明できますか?
ありがとう。