简体   繁体   中英

Segmentation fault with GDB debugger - C

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

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.

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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM