2012-09-30 35 views
2

這裏是我的代碼,它在這裏出錯strcpy(pSrcString,"muppet");事實上,它每當我使用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; 
} 

回答

9

您已經(pSrcString = malloc(7) == NULL)放錯了地方的括號內。這樣,您首先檢查malloc(7)NULL(其結果爲false或0)的結果,然後將其分配給pSrcString。基本上是:

pSrcString = 0; 

當然是不會給你一個有效的內存,讓strcpy寫東西的嘛。試試這個:

(pSrcString = malloc(7)) == NULL 

同樣爲pDstString

另外,如果你只是想要一個字符串的副本,你可以使用strdup函數。那爲你分配記憶並照顧計算長度本身:

pSrcString = strdup("muppet"); 
相關問題