#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程序出了什么问题?
发布于 2012-08-12 20:39:00
如果我不使用strdup,则使用
。分配"char *bp = buf“。然后,上面的程序将分割故障。
它可能必须使用buf指向不能合法写入的内存,在本例中是字符串文字。如果您使用strdup,您将写入您自己的可写副本。
https://stackoverflow.com/questions/11922222
复制相似问题