2014-12-01 68 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 

    }