[英]What is causing this strcpy segfault?
這是我的代碼,它在這里出現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;
}
您在(pSrcString = malloc(7) == NULL)
放錯了括號。 這樣,您首先檢查malloc(7)
的結果是否為NULL
(結果為false或0
),然后將其分配給pSrcString
。 基本上:
pSrcString = 0;
當然,這不會給你一個有效的內存讓strcpy
寫東西。 試試這個:
(pSrcString = malloc(7)) == NULL
同樣對於pDstString
。
另外,如果您只想擁有該字符串的副本,則可以使用strdup
函數。 為您分配內存並負責計算長度本身:
pSrcString = strdup("muppet");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.