cgdb
b 31 if letter=='1'
How to find segfaults
-
Compile and run your code
-
We can see that there is a segfault, but we do not know where it is occuring.
-
Let’s open up the code in cgdb (make sure that u compiled it with the -g flag)
-
Recall the
runcommand will run your code until something stops it (like a segfault or a breakpoint). Execute theruncommand. -
The command windows shows us that the program encountered a segfault (“Program received signal SIGSEGV”) at line 62. Now we know the line where the segfault occured.
-
Another command that can be useful when u are debugging segfaluts is backtrace. This will allow u to see the call stack at the time of the crash. Execute the following command to see the call stack.
backtraceor
bt - Let’s examine the state of the program when the segfault occured by printing some variables. Print out head.
- Remember that
headis a double pointer, so we expect to see an address when we print it out.headlooks fine. Let’s print out the dereferenced head (*head). - It looks like
*headisNULL. If you look at the line of code that the program is segfaulting on, you can see that we are trying to access(*head)->next. We know that trying to access a member of aNULLstruct will result in a segfault, so this is our problem. - What does it mean for
*headto be NULL? It means that the list is empty. How do we reverse an empty list? The reverse of an empty list is just an empty list, so we do not need to modify the list. At the top of the function, we can add a check to see if the list if empty and return if so. Modify the first line of the function to be the following: - Compile and run your code. It should pass the reverse list tests now.
Other Useful GDB Commands
**Command: **info locals
Print the values of all the local variables in the current stack frame
**Command: **command
Execute a list of commands every time a break is reached.
For example:
Set a breakpoint:
b 73
Type commands followed by the breakpoint number:
commands 1
Type the list of commands that you want to execute separated by a new line. After your list of commands, type end and hit Enter.
p var1
p var2
end
**Command: ** delete
Deletes the specified breakpoint.