Let's take it from step 1.
If you are using gcc/g++ to compile your program, add the "-g" flag in while you compile your program. This will prevent the compiler from changing function or variable names for optimisation.
g++ -g -o main main.cpp
Okay, so now you have compiled your executable with debugging symbols loaded.
Now you may want to test your program with the ordinary approach of
... but let's not do that.
This time, try this (AND DO NOT PUT ARGUMENTS OR PIPES IN IT
This will start up GDB and tell it "We are wanting to run main
in our debugger".
GDB is a command interface on its own too.
It has its own commands.
I'll put a list/cheatsheet below, but for now, let's run GDB.
command will run the executable.
NOTE: If you wanted to run the program with a pipe or arguments, you can do it via run as well...
run arg1 arg2 < file_in > file_out
Now, assuming your code just failed, it will tell you the issue and where it is in your code.
Hence the screenshot:
This screenshot also has 3 more commands featured... backtrace
, and print
With these, you can navigate the program's stack frame
, to go to a particular function and get variable values, etc.
In the screenshot above, everything is happening only in main(), so it's the only function in the stack trace. So if we call this:
We will go to frame 0 in the code, which is your main() function.
Then, since p is a variable in that function's scope, we can grab the value of it.
It prints out
(int *) 0x0
, which is basically an invalid pointer.
The variable is declared, but not initialised, so there's the problem in our code.
So Ctrl+C doesn't kill it. How do I quit gdb?