【问题标题】:C - segfault when using strcmp()C - 使用 strcmp() 时的段错误
【发布时间】:2016-04-03 21:33:49
【问题描述】:

使用 strcmp() 时出现段错误。我尝试使用 gdb 进行调试,当我运行它(不带参数)时,我得到一个段错误。当我回溯时,它表明段错误位于第 20 行,但我无法弄清楚它为什么会出现段错误。 strcmp() 语句在第 20 行。我将在我的帖子中包含第 0-21 行,但如果需要可以添加更多。

我使用run命令时的segfault语句如下:

Program received signal SIGSEGV, Segmentation fault.
__strcmp_sse2 () at ../sysdeps/x86_64/multiarch/../stcmp.S:213
213 ../sysdeps/x86_64/multiarch/../strcmp.S: No such file or directory.

然后我做一个backtrace 并得到这个:

#0 __strcmp_sse2 () at ../sysdeps/x86_64/multiarch/../strcmp.S:213
#1 0x0000000000400aa6 in main (c=1, v=0x7fffffffead8) at myls.c:20

这是我第 0-21 行的代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <time.h>
#include <fcntl.h>
#include <pwd.h>
#include <string.h>
#include <grp.h>

int main(int c, char *v[])
{
    DIR *directory = NULL;
    strut direct *dir_pointer = NULL;
    int i = 0;
    char cwd[1024];

    if(strcmp(v[1], "-i") == 0){ //line 20, where the segfault happens
        ...

任何提示/帮助表示赞赏。

【问题讨论】:

  • “当我运行它时(不带参数)” - 嗯???你让 better 至少提供一个参数,或者按照标准 v[1] 为 NULL; strcmp 不能很好地与 NULL 配合使用,因为它的 either 参数。
  • @WhozCraig 这方面的一些背景知识:我正在编写自己的 ls 程序来模仿 unix ls 命令。当我使用./myls 运行它时,c=1 是否正确?当我使用./myls -l 运行它时,c = 2?和-l = v[1]?
  • 我强烈建议您仔细read the q&a at the link 下面由 Kons 提供。它回答了这个问题,还有很多,很多

标签: c segmentation-fault gdb strcmp


【解决方案1】:

您正在调用不带参数(c = 1)并访问给程序的第一个参数(好像 c 是 2)..

我建议你阅读这个答案

What does int argc, char *argv[] mean?

【讨论】:

  • 这与找不到“strcmp.S”有什么关系?因为错误是“没有这样的文件或目录。”
【解决方案2】:

您要么没有将参数传递给程序,要么在if 语句之后直接出现段错误。 strcmp 有效。

编辑:刚刚意识到你不会在没有参数的情况下传递它。当没有v[1] 时,您引用的是v[1]

【讨论】:

  • 但是我有一个 elif 语句,上面写着 else if(c&lt;2){,我还应该得到一个段错误吗?
  • 是的,因为您首先评估v[1]
  • 那么我应该让if(c&lt;2) 成为第一个声明吗?这会解决它吗?
  • 是的,或者你可以这样做c&gt;=2 &amp;&amp; strcmp(v[1], "-i") == 0
  • 评论了它,它正在打印“它有效”....我想我还有一些修复要做哈哈
猜你喜欢
  • 1970-01-01
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 2015-08-14
  • 2021-06-11
  • 1970-01-01
  • 2011-09-12
  • 1970-01-01
相关资源
最近更新 更多