Strlen导致段错误

时间:2013-11-25 21:16:44

标签: c

我对理解strlen和/或memcpy有疑问。 这是片段:

char * restP;
char * str;
//this returns a pointer 
restP = strrstr (input_buffer, "pointer");
//this prints this pointer
printf("%p\n", restP);

str = malloc( 50000);

//this is wrong, restP is a pointer to a sring; i can print it with printf("%s", restP); it just a part of input_buffer

memcpy(restP, str, strlen(restP)-1 );

strlen(restP)给我一个错误 - segmentation fault. 也许有人可以告诉我我做错了什么。

2 个答案:

答案 0 :(得分:4)

Strlen对字符进行计数,直到它到达NUL('\ 0')字符。确保您的字符串包含此字符,否则strlen将计算数组边界,即出现分段错误的情况。 C不提供数组边界检查。

另外,检查您传递的指针是否有效(即它不为空)。

答案 1 :(得分:3)

看起来你memcpy的论据是错误的。第一个参数是目的地,第二个参数是。您好像要将restP的内容复制到str

memcpy(str, restP, strlen(restP) + 1);

我在restP的长度中添加了一个,这样也会复制空字符(不会将其视为strlen的一部分。您不需要从{减去一个} {1}}除非:

  1. 您知道strlen足够长并且初始化为零,因此复制到其中的任何适当大小的字符串都将以空字符终止。

  2. 您不想复制源字符串的最后一个字符。