c - 给出段错误和 idk 在哪里

标签 c segmentation-fault

我正在用 C 编写一个程序,用户输入一些内容,如果其中一个单词在数组中(在本例中是 biblio),但是当我要测试它时给我段错误(核心转储)。 我知道当程序尝试访问它无法访问的内存字段时会出现此错误,但我找不到它在哪里执行此操作以及如何修复它。有人可以帮助我吗?

 #include <stdio.h>
 #include <string.h>

int within(char* str, char * biblio[], int size)
{
    char * aux;
    for(int i = 0; i < size; i++)
    {
        aux = biblio[i];
        if(strcmp(str, aux) == 0 )
            return 1; //return 1 --> the word exists in biblio array
    }
    return 0;
}

int main()
{
    int iterations = 5;
    int size = 50, count = 0;
    char * biblio[] = {"mostarda", "ketchup", "maionese"};
    char * input[size];
    char * str = NULL;
    int ret;
    while(iterations > 0)
    {
        do{
            printf("Enter a value: ");
            scanf("%s", str);
            ret = within(str, biblio, sizeof (biblio));
            if(ret == 1)
            {
                memset(input, 0, sizeof(input)); //clear biblio
                break;
            }
            input[count] = str;
            count++;
        }while( (strcmp(str, "EOF")) == 0);

        printf("%s", input);
        iterations--;
    }
    return 0;
}

非常感谢!!!

最佳答案

通常,使用 gcc -g 进行编译以进行调试,然后在 gdb 下运行二进制文件。当它核心转储时,给 gdb 提供 where 命令来查看完整的调用堆栈,显示程序中失败的行号。

例如,这是我的 gdb session 找出原因的过程。我使用 gdb ./a.out 在 gdb 中运行程序,然后输入测试值。当它崩溃时,它显示错误出现在 strcmp 的(程序集)实现中(我没有该库源文件,因此“没有这样的文件或目录”。我去 up 1 将 View 在堆栈中向上移动一级(进入您的 within 函数),然后我将两个参数的值打印到 strcmp。一其中显然不符合应有的样子。

Reading symbols from ./a.out...done.
(gdb) run
Starting program: /tmp/p/a.out 
Enter a value: 10

Program received signal SIGSEGV, Segmentation fault.
__strcmp_sse2_unaligned () at ../sysdeps/x86_64/multiarch/strcmp-sse2-unaligned.S:31
31  ../sysdeps/x86_64/multiarch/strcmp-sse2-unaligned.S: No such file or directory.
(gdb) up 1
#1  0x00005555555547f4 in within (str=0x0, biblio=0x7fffffffe450, size=24) at foo.c:11
11          if(strcmp(str, aux) == 0 )
(gdb) print (str)
$1 = 0x0
(gdb) print (aux)
$2 = 0x555555554a44 "mostarda"

关于c - 给出段错误和 idk 在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50571180/

相关文章:

c - 为什么在写入使用字符串文字初始化的 "char *s"而不是 "char s[]"时出现段错误?

冒泡排序变体中的 C 段错误

C/链表/如何修复段错误?

通过 tp_getset 访问时 Python C 扩展出现段错误

c - 如何使这个循环适用于我的回文测试?

c - 尝试从命令行获取星号 * 作为对 main 的输入

c - 如何在 Ubuntu 中正确使用 AES_CBC_Encrypt 128 openssl?

c - 获取C 中函数的地址?

c - C/Linux 指针到指针的段错误

C 堆栈分配大小