【问题标题】:Segmentation fault strcmp in cc中的分段错误strcmp
【发布时间】:2015-08-14 12:14:05
【问题描述】:

我正在尝试在 c 中运行一个程序,该程序从用户那里获取一个文本文件和字符串,然后在文件中搜索该字符串。它不断出现分段错误,gdb 将我指向此功能,但我不确定问题出在哪里。我很确定这与strcmp 通话有关,但我不确定。对此问题的任何帮助将不胜感激。

int inTable( const char *s )
{
    int i;

    for( i=0; i<numLines; ++i )
    {
        if( strcmp( st[i], s ) == 0 )
                return 1;
    }

    return 0;
}

【问题讨论】:

  • st 是使用 fgets() 读入的文件
  • @user4959809 ,stFILE* 吗?

标签: c debugging segmentation-fault gdb strcmp


【解决方案1】:

我认为你应该检查一下:

int inTable(const char *s) 
{
     if (s == NULL)
     {
          return 0;
     }

     // invoke strcmp
}

确保 const char *s 以 '\0

结束

【讨论】:

    【解决方案2】:

    您应该检查您是否正确使用strcmp(),API 是:

    int strcmp(const char *str1, const char *str2)
    

    你必须:

    1) 验证st[i],您的第一个参数是一个指针。

    2) 确保 st[i]s 具有 Null 终止符 '\0'`。

    3) 在调用strcmp() 之前检查st[i]s 是否指向内存中分配的位置。

    【讨论】:

      猜你喜欢
      • 2011-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      • 2020-08-25
      相关资源
      最近更新 更多