是什么导致这个strcpy segfault?

Dan*_*nyK 2 c malloc strcpy

这是我的代码,它在这里出错strcpy(pSrcString,"muppet");.事实上,无论什么时候我使用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;
}
Run Code Online (Sandbox Code Playgroud)

Lek*_*eyn 9

你错了你的括号了(pSrcString = malloc(7) == NULL).通过这种方式,您首先检查malloc(7)反对的结果NULL(结果是假或0),然后将其分配给pSrcString.基本上:

pSrcString = 0;
Run Code Online (Sandbox Code Playgroud)

当然,这不会给你一个有效的记忆让你strcpy写东西.试试这个:

(pSrcString = malloc(7)) == NULL
Run Code Online (Sandbox Code Playgroud)

同样地pDstString.

另外,如果您只想拥有该字符串的副本,则可以使用该strdup功能.为您分配内存并负责计算长度本身:

pSrcString = strdup("muppet");
Run Code Online (Sandbox Code Playgroud)