在不同的字符串指针/数组类型strsep段错误 [英] strsep segmentation faults on different string pointer/array types
问题描述
平台:Linux,OSX结果
编译器:GCC
我有一个简单的程序,这是目前混杂我 - 我知道我有一对夫妇搞乱不同种类的阵列/指针产生这个问题 - 它的故意 - 我试图去了解它
在code作为上市将编译并运行如预期,但改变数据4
(放大器在调用 strsep; DATA4 E);
到数据1
或 DATA3
导致分段错误。我想知道为什么。
的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;INT主(INT C,焦炭** V){
字符* DATA1 =你好\\ 0;
字符*数据2 =的strdup(数据1);
为size_t SZ = strlen的(数据1);
CHAR数据3 [SZ + 1];
字符* DATA4; memset的(DATA3,0,SZ + 1);
DATA4 =函数strncpy(数据3,数据1,SZ);
DATA4 [深圳] ='\\ 0'; 字符*发现= strsep(安培;数据4,E); 如果(找到== NULL){
输出(没有找到\\ n);
}其他{
的printf(发现ê\\ n);
} 返回0;
}
在调用改变数据4至strsep(安培;数据4,E);为DATA1或DATA3导致分段错误。
块引用>在这种情况下:
的char *发现= strsep(安培;数据1,E);
该字符串由
数据1
是文字,因此不能改变指向。当strsep()
尝试将'\\ 0'的地方进去,段错误。在另一种情况:
的char *发现= strsep(安培;数据3,E);
DATA3
是一个数组,而不是一个指针(即使阵列轻松地评估为指针,它们实际上不是指针),所以strsep()
无法更新指针,是它试图做一次找到令牌的值。我从GCC尝试以下警告指出这一点:test.c的:17:警告:从兼容的指针类型传递'strsep'的参数1
Platform: Linux, OSX
Compiler: GCCI'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 tostrsep(&data4, "e");
todata1
ordata3
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; }
解决方案changing data4 in the call to strsep(&data4, "e"); to data1 or data3 causes a segmentation fault.
In this case:
char* found = strsep(&data1, "e");
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:
char* found = strsep(&data3, "e");
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:test.c:17: warning: passing argument 1 of 'strsep' from incompatible pointer type
这篇关于在不同的字符串指针/数组类型strsep段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!