Segmentation fault with GDB debugger - C

半世苍凉 提交于 2019-12-08 13:55:48

问题


I am trying to "debug" this program using GDB debugger. I get the Segmentation fault (core dumped) when I execute the program. This is my first time using GDB, so I do not really know what command to use or what to expect.

EDIT: I know what the error is. I need to find it using the GDB Debugger

This is the code:

#include <stdio.h>

int main()
{
    int n, i;
    unsigned long long factorial = 1;

    printf("Introduzca un entero: ");
    scanf("%d",n);

    if (n < 0)
        printf("Error! Factorial de un numero negativo no existe.");

    else
    {
        for(i=0; i<=n; ++i)
        {
            factorial *= i;
        }
        printf("Factorial de %d = %llu", n, factorial);
    }

    return 0;
}

回答1:


Here is the problem:

scanf("%d",n);

As you wrote, n is declared as a variable of type int. What you want to do is to pass the address of n instead of n itself into the function.

scanf("%d", &n);

To better understand the implementation of scanf(), check out stdio.h.

Also, set n = 1. Or otherwise the variable factorial will remain 0 regardless how many loops you've gone through.

EDIT: what you are trying to do to is to access a memory location passed in by the user, which is highly likely to map to a memory location that belongs to a completely different process or even OS. The segmentation fault is generated simply because the location is not accessible. What you can do in gdb is using bt in the gdb to a stack trace of segmentation fault.




回答2:


I know what the error is. I need to find it using the GDB Debugger

You need to read the documentation of gdb (and you should compile your source code with all warnings and debug info, e.g. gcc -Wall -Wextra -g with GCC; this puts DWARF debug information inside your executable).

The GDB user manual contains a Sample GDB session section. You should read it carefully, and experiment gdb in your terminal. The debugger will help you to run your program step by step, and to query its state (and also to analyze core dumps post-mortem). Thus, you will understand what is happening.

Don't expect us to repeat what is in that tutorial section.

Try also the gdb -tui option.

PS. Don't expect StackOverflow to tell you what is easily and well documented. You are expected to find and read documentation before asking on SO.



来源:https://stackoverflow.com/questions/46749834/segmentation-fault-with-gdb-debugger-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!