【问题标题】:strcpy Seg Faultstrcpy 段错误
【发布时间】:2014-12-01 21:43:51
【问题描述】:

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

【问题讨论】:

  • 如果任一名称超过 31 个字符,它将写入无效内存,因为您创建的缓冲区只有那么大。
  • 名字平均只有5-10个字符
  • 我猜firstsecondNULL。使用调试器。
  • 需要向我们展示调用代码,以便我们知道firstsecond 是什么。其次当然是为什么要打扰strcpy 电话。为什么不在PERSON.name 字段上使用strcmp
  • 好的,你确定 first 和 second 总是非空的,并且它们的名字都是非空的吗?

标签: c segmentation-fault strcpy


【解决方案1】:

似乎 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 );

或者您可以将此断言拆分为几个单独的断言。

【讨论】:

  • 长度为 32 的零终止数据呢?
  • @Deduplicator 例如 first->data 是指向动态分配数据的指针,该数据大小为 32 个字符,但包含非零终止数据。
【解决方案2】:
 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

   }

~

【讨论】:

    猜你喜欢
    • 2014-06-15
    • 1970-01-01
    • 2020-10-05
    • 2014-10-21
    • 2013-02-23
    • 2019-02-23
    • 2017-03-12
    • 2017-09-17
    • 2018-07-28
    相关资源
    最近更新 更多