Segfault analysis with GDB
suggest changeLet's use the same code as above for this example. Reading uninitialized p1 to initialize p3, then testing if (p3), is undefined behavior. In the session below the condition was true, so execution reached the null dereference of p2. The transcript names debugging_with_gdb.cc, not this listing.
#include <iostream>
void fail() {
int *p1;
int *p2(nullptr);
int *p3 = p1;
if (p3) {
std::cout << *p2 << std::endl;
}
}
int main() {
fail();
}
First let's compile it
g++ -g -o main main.cpp
Let's run it with gdb
gdb ./main
Now we will be in gdb shell. Type run.
(gdb) run
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/opencog/code-snippets/stackoverflow/a.out
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400850 in fail () at debugging_with_gdb.cc:11
11 std::cout << *p2 << std::endl;
We see the segmentation fault is happening at line 11. So the only variable being used at this line is pointer p2. Let's examine its content typing print.
(gdb) print p2
$1 = (int *) 0x0
Now we see that p2 was initialized to 0x0, the null pointer value. At this
line, we know that we are trying to dereference a null pointer, so we fix it.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents