2014-12-01 6 views
-1

DDD에 따르면 나는 strcpy에서 seg fault를 얻고있다. 그러나 내가 잘못하고있는 것을 (아직도 C에서 아주 새로운) 이해할 수는 없다. 어떤 도움이라도 미리 감사드립니다.strcpy Seg 결함

int compare_people(PERSON* first, PERSON* second) 
{ 
    char firstName[32]; 
    char secondName[32]; 

    strcpy(firstName, first->name); 
    strcpy(secondName, second->name); 

    int returnVal = strcmp(firstName, secondName); 

    return returnVal; 
} 
+2

, 그것은 잘못된 메모리에 기록합니다. – mukunda

+0

이름은 평균 5-10 자입니다. – Sammdahamm

+2

'first' 또는'second'가'NULL'이라고 생각합니다. 디버거를 사용하십시오. –

답변

2

는 이름이 null거나 동일한 기인의 strcpy를 사용하여 32 개 개의 문자를 초과하는 비 - 제로 종료 데이터가> 첫 번째 또는 두 번째 하나가 NULL 같거나 1 세대> 이름 또는 2 ~ 것 같다. 다른 이유는 first-> name 또는 second-> name에 유효하지 않은 포인터 (예 : 이미 삭제 된 로컬 데이터에 대한 포인터)가있는 것일 수 있습니다.

기능을 삽입하십시오. 예를 들어

assert(first != NULL && second != NULL && 
     first->name != NULL && second->name != NULL && 
     strlen(first->name) < 32 && strlen(second->name) < 32); 

또는 여러 개의 개별 어설 션으로이 어설 션을 분리 할 수 ​​있습니다. 두 이름은 더 이상 31 개 문자보다 길 경우 당신이 만든 버퍼가 아니라 큰 있기 때문에

+0

길이가 32 인 제로 종료 데이터는 어떻게됩니까? – Deduplicator

+0

@Deduplicator 예를 들어, first-> data는 크기가 32 자이지만 종료되지 않은 데이터가 0이 아닌 동적으로 할당 된 데이터에 대한 포인터입니다. –

0
just try that code. 

    #include <stdio.h> 
    #include <stdlib.h> 
    #include <string.h> 
    typedef struct{ 

    char name[25]; 
    }PERSON; 

    int compare_people(PERSON* first, PERSON* second); 
    main() 
    { 
    PERSON *first,*second; 
    first=(PERSON *)malloc(sizeof(PERSON)); 
    printf("Enter the first name\n"); 
    scanf("%s",first->name); 
    second=(PERSON *)malloc(sizeof(PERSON)); 
    printf("Enter the second name\n"); 
    scanf("%s",second->name); 

    if((compare_people(first,second)) == 0) 
     printf("Two names are same \n"); 
    else 
     printf("Two names are different\n"); 


    } 

    int compare_people(PERSON* first, PERSON* second) 
    { 
    char firstName[32]; 
    char secondName[32]; 

    strcpy(firstName, first->name); 
    strcpy(secondName, second->name); 

    int returnVal = strcmp(firstName, secondName); 
    return returnVal 

    } 

~