Aidin
Aidin

Reputation: 3

How to find the line caused segmentation fault in c++ compiled program

I am using vim for c++ programming. I have bound the compile command to ctrl+c in vim and I run it in another tmux pane by running ./main.out. My problem is that when my c++ program gives me segmentation fault error, I don't know which line has caused the problem. But when I compiled and ran the program in vscode, it showed me the line that caused the error. I'm seeking for a way to find out the lines that cause runtime errors like segmentation fault error while running the program's binary file in console. This is an example output when I do ./main.out:

[1]    24656 segmentation fault (core dumped)  ./main.out

Upvotes: 0

Views: 1697

Answers (1)

cigien
cigien

Reputation: 60208

When compiling the program, add the -g compiler flag, or even better -ggdb3, which will give you a much prettier output, by adding debugging symbols to the executable. Also, make sure that you compile with the -O0 optimization level.

To actually debug the program, run gdb ./main.out to start the program in a debugging session. If you then run r, gdb will start executing the program, and then stop at the line that gives the segfault.

To figure out how you got to that point, run bt while in the debugging session, and you will get a backtrace, which will show you all the function calls that were made to get to the line of code that crashed.

You can of course do a lot more than this (and you will probably need to, since locating the source of an error is often only the first step). You can use p to print the values of variables, set watchpoints, and many more things. For a while now, gdb even ships with a full fledged python interpreter, so you can even write a python script for your custom debugging needs.

Learning how to use gdb can seem overwhelming at the start, but persevere, and I guarantee the effort will pay off big time :)

Upvotes: 3

Related Questions