2012-09-30 6 views
2

내 코드는 여기에 있습니다. strcpy(pSrcString,"muppet"); strcpy를 사용할 때마다 실제로 작동합니다.이 strcpy segfault의 원인은 무엇입니까?

#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 (거짓 또는 0)으로 확인한 다음 pSrcString에 할당합니다. 기본적으로 :

pSrcString = 0; 

그럼 당신에게로 strcpy 쓰기 일을 할 수있는 유효한 메모리를 제공하지 않을 물론. 대신 다음을 시도하십시오 :

(pSrcString = malloc(7)) == NULL 

pDstString에 대해서도 마찬가지입니다.

문자열의 복사본을 갖고 싶으면 strdup 함수를 사용할 수 있습니다. 그러면 메모리가 할당되고 길이 자체를 계산합니다.

pSrcString = strdup("muppet"); 
관련 문제