簡體   English   中英

strcpy段故障

[英]strcpy Seg Fault

根據DDD,我從strcpy得到了段錯誤,但是我不太清楚自己在做什么錯(對C來說還是很新的)。 任何幫助將不勝感激,在此先感謝。

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;
}

似乎first或second等於NULL或first-> name或second-> name等於NULL或由於使用strcpy而導致的非零終止數據超過了32個字符。 另一個原因可能是first-> name或second-> name的指針無效,例如,指向已銷毀的本地數據的指針。

在函數中插入一個檢查。 例如

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

或者,您可以將此斷言拆分為幾個單獨的斷言。

 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

   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM