2

这是我的代码,它在这里出错了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;
}
4

1 回答 1

9

你把括号放错了(pSrcString = malloc(7) == NULL)。这样,您首先检查malloc(7)against的结果NULL(结果是 false 或0),然后将其分配给pSrcString. 基本上:

pSrcString = 0;

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

(pSrcString = malloc(7)) == NULL

同样对于pDstString.

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

pSrcString = strdup("muppet");
于 2012-09-30T09:38:58.950 回答