How to Debug Segmentation Fault

Fixing Segmentation faults in C++

  1. Compile your application with -g, then you'll have debug symbols in the binary file.

  2. Use gdb to open the gdb console.

  3. Use file and pass it your application's binary file in the console.

  4. Use run and pass in any arguments your application needs to start.

  5. Do something to cause a Segmentation Fault.

  6. Type bt in the gdb console to get a stack trace of the Segmentation Fault.

Determine the line of code that causes a segmentation fault?

GCC can't do that but GDB (a debugger) sure can. Compile you program using the -g switch, like this:

gcc program.c -g

Then use gdb:

$ gdb ./a.out
(gdb) run
<segfault happens here>
(gdb) backtrace
<offending code is shown here>

Here is a nice tutorial to get you started with GDB.

Where the segfault occurs is generally only a clue as to where "the mistake which causes" it is in the code. The given location is not necessarily where the problem resides.

How to debug a Python segmentation fault?

I got to this question because of the Segmentation fault, but not on exit, just in general, and I found that nothing else helped as effectively as faulthandler. It's part of Python 3.3, and you can install in 2.7 using pip.

When I run my code, i get a segfault, but when the debugger runs it, it says there is no issue

Run your program with valgrind. It will detect invalid reads and writes to memory, tell you where they happen and, most likely, be helpful enough to tell you exactly what line caused them. One of these errors is what's causing your program to segfault.

Don't forget to add the -ggdb3 flag when compiling your program :)

Segmentation Fault in Visual Studio Code while debug C Program

For starters this call

fflush(stdin);

has undefined behavior. Remove it.

Secondly in this call of scanf

scanf("%c", &ch);

you should prepend the conversion specifier with a space

scanf(" %c", &ch);
^^^^^

Otherwise white space characters as the new line character '\n' will be read.

The pointer str is not initialized and has an indeterminate value

char* str;

So this call

scanf("%s", str);

invokes undefined behavior.

You should declare a character array as for example

char str[100];

and call the function scanf like

scanf("%99s", str);


Related Topics



Leave a reply



Submit