[contents]
[usage]
[execution]
[stack]
[breakpoints]
[watchpoints]
[advanced]
7.2 Example Debugging Session: Segmentation Fault ExampleWe are going to use gdb to figure out why the following program causes a segmentation fault. The program is meant to read in a line of text from the user and print it. However, we will see that in it's current state it doesn't work as expected...
The first step is to compile the program with debugging flags:
Now we run the program:
This is not what we want. Time to fire up gdb:
We'll just run it and see what happens:
So we received the SIGSEGV signal from the operating system. This means that we tried to access an invalid memory address. Let's take a backtrace:
We are only interested in our own code here, so we want to switch to stack frame 3 and see where the program crashed:
We crashed inside the call to fgets. In general, we can assume that library functions such as fgets work properly (if this isn't the case, we are in a lot of trouble). So the problem must be one of our arguments. You may not know that 'stdin' is a global variable that is created by the stdio libraries. So we can assume this one is ok. That leaves us with 'buf':
The value of buf is 0x0, which is the NULL pointer. This is not what we want - buf should point to the memory we allocated on line 8. So we're going to have to find out what happened there. First we want to kill the currently-running invocation of our program:
Now set a breakpoint on line 8:
Now run the program again:
We're going to check the value of buf before the malloc call. Since buf wasn't initialized, the value should be garbage, and it is:
Now step over the malloc call and examine buf again:
After the call to malloc, buf is NULL. If you were to go check the man page for malloc, you would discover that malloc returns NULL when it cannot allocate the amount of memory requested. So our malloc must have failed. Let's go back and look at it again:
Well, the value of the expression 1 << 31 (the integer 1 right-shifted 31 times) is 429497295, or 4GB (gigabytes). Very few machines have this kind of memory - mine only has 256MB. So of cousre malloc would fail. Furthermore, we are only reading in 1024 bytes in the fgets call. All that extra space would be wasted, even if we could allocate it. Change the 1<<31 to 1024 (or 1<<9), and the program will work as expected:
So now you know how to debug segmentation faults with gdb. This is extremely useful (I use it more often then I care to admit). The example also illustrated another very important point: ALWAYS CHECK THE RETURN VALUE OF MALLOC! Have a nice day. [contents] [usage] [execution] [stack] [breakpoints] [watchpoints] [advanced] Questions? Comments? Flames? email rms@unknownroad.com |