gpt4 book ai didi

strsep - 为什么strsep段错误

转载 作者:行者123 更新时间:2023-12-04 18:14:54 25 4
gpt4 key购买 nike

#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

程序有什么问题?

最佳答案

If I don't use strdup. assign "char *bp = buf". then the above programe will segment fault.



它可能需要使用 buf指向不能合法写入的内存,在这种情况下是字符串文字。如果您使用 strdup您将写入自己的可写副本。

关于strsep - 为什么strsep段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11922222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com