不同字符串指针/数组类型上的 strsep 分段错误
平台:Linux、OSX
编译器:GCC
我有一个简单的程序,目前让我感到困惑 - 我知道我正在弄乱几种不同类型的数组/指针来产生这个问题 - 这是故意的 - 我正在尝试理解它。
列出的代码将按预期编译和运行,但将 strsep(&data4, "e");
调用中的 data4
更改为 data1
code> 或 data3
导致分段错误。我想了解为什么。
#include <stdio.h>
#include <string.h>
int main(int c, char** v) {
char* data1 = "hello\0";
char* data2 = strdup(data1);
size_t sz = strlen(data1);
char data3[sz+1];
char* data4;
memset(data3, 0, sz+1);
data4 = strncpy(data3, data1, sz);
data4[sz] = '\0';
char* found = strsep(&data4, "e");
if (found == NULL) {
printf("nothing found\n");
} else {
printf("found e\n");
}
return 0;
}
Platform: Linux, OSX
Compiler: GCC
I've got a simple program which is currently confounding me - I know that I'm messing with a couple different kinds of arrays/pointers to produce this problem - its intentional - I'm trying to understand it.
The code as listed will compile and run as expected, but changing data4
in the call to strsep(&data4, "e");
to data1
or data3
causes a segmentation fault. I would like to understand why.
#include <stdio.h>
#include <string.h>
int main(int c, char** v) {
char* data1 = "hello\0";
char* data2 = strdup(data1);
size_t sz = strlen(data1);
char data3[sz+1];
char* data4;
memset(data3, 0, sz+1);
data4 = strncpy(data3, data1, sz);
data4[sz] = '\0';
char* found = strsep(&data4, "e");
if (found == NULL) {
printf("nothing found\n");
} else {
printf("found e\n");
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在本例中:
data1
指向的字符串是文字,因此无法更改。当strsep()
尝试将 '\0' 放入其中时,会出现段错误。在另一种情况下:
data3
是一个数组,而不是指针(即使数组很容易计算为指针,但它们实际上不是指针),因此strsep()
无法更新指针的值,这就是它找到令牌后尝试执行的操作。我从 gcc 收到以下警告,试图指出这一点:In this case:
the string pointed to by
data1
is a literal so it cannot be changed. Whenstrsep()
tries to place a '\0' into it, segfault.in the other case:
data3
is an array, not a pointer (even though arrays easily evaluate to pointers, they are not actually pointers), sostrsep()
cannot update the value of the pointer which is what it tries to do once it finds the token. I get the following warning from gcc attempting to point this out: