#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char *buf = "2012/9/8";
char sep[] = "/";
char *token;
// char *bp = strdup(buf);
char *bp = buf;
while ((token = strsep(&bp,sep))) {
printf("tok = `%s'\n", token);
}
free(bp);
return 0;
}
如果我不使用 strdup。分配“char *bp = buf”。那么上面的程序就会出现段错误。gdb 输出如下:
Program terminated with signal 11, Segmentation fault.
#0 0x00007fcc949c13b5 in strsep () from /lib/x86_64-linux-gnu/libc.so.6
(gdb) bt
#0 0x00007fcc949c13b5 in strsep () from /lib/x86_64-linux-gnu/libc.so.6
#1 0x00000000004005d5 in main () at str_split.c:11
程序有什么问题?