2014-12-01 65 views
-1

根據DDD我從strcpy中得到一個seg錯誤,但我無法弄清楚我做錯了什麼(對C來說還是很新的)。任何幫助將不勝感激,在此先感謝。strcpy Seg Fault

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

如果name是超過31個字符長,將會寫入無效的內存,因爲你做的緩衝區是唯一的那麼大。 – mukunda 2014-12-01 21:45:41

+0

這些名字平均只有5-10個字符 – Sammdahamm 2014-12-01 21:46:02

+2

我猜'first'或'second'是'NULL'。使用調試器。 – 2014-12-01 21:46:44

回答

2

似乎第一或第二等於NULL或一線>名稱或二線>名等於NULL或具有非零終止的數據,由於使用的strcpy超過32個字符。 另一個原因可能是first-> name或second->名稱具有無效指針,例如指向已經銷燬的本地數據的指針。

在功能中插入一個檢查。例如

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

或者你可以將這個斷言拆分成幾個單獨的斷言。

+0

長度爲32的零終止數據如何? – Deduplicator 2014-12-01 21:54:49

+0

@Deduplicator例如first-> data是一個指向動態分配數據的指針,它的大小爲32個字符,但包含非零終止數據。 – 2014-12-01 21:56:36

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 

    }