[英]What is causing this strcpy segfault?
Here is my code and it faults here strcpy(pSrcString,"muppet");
这是我的代码,它在这里出现
strcpy(pSrcString,"muppet");
Well infact it does whenever I use strcpy. 事实上,每当我使用strcpy时它都会这样做。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *pSrcString = NULL;
char *pDstString = NULL;
/* muppet == 6, so +1 for '\0' */
if ((pSrcString = malloc(7) == NULL))
{
printf("pSrcString malloc error\n");
return EXIT_FAILURE;
}
if ((pDstString = malloc(7) == NULL))
{
printf("pDstString malloc error\n");
return EXIT_FAILURE;
}
strcpy(pSrcString,"muppet");
strcpy(pDstString,pSrcString);
printf("pSrcString= %s\n",pSrcString);
printf("pDstString = %s\n",pDstString);
free(pSrcString);
free(pDstString);
return EXIT_SUCCESS;
}
You have misplaced your parentheses in (pSrcString = malloc(7) == NULL)
. 您在
(pSrcString = malloc(7) == NULL)
放错了括号。 In that way, you are first checking the result of malloc(7)
against NULL
(which turns out to be false or 0
), and then assigns that to pSrcString
. 这样,您首先检查
malloc(7)
的结果是否为NULL
(结果为false或0
),然后将其分配给pSrcString
。 Basically: 基本上:
pSrcString = 0;
Well of course that is not going to give you a valid memory to let strcpy
write things to. 当然,这不会给你一个有效的内存让
strcpy
写东西。 Try this instead: 试试这个:
(pSrcString = malloc(7)) == NULL
Likewise for pDstString
. 同样对于
pDstString
。
Aside, if you just want to have a copy of the string, you can use the strdup
function. 另外,如果您只想拥有该字符串的副本,则可以使用
strdup
函数。 That allocates memory for you and takes care of calculating the length itself: 为您分配内存并负责计算长度本身:
pSrcString = strdup("muppet");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.