UMBC CMSC 201 Fall '05
CSEE | 201 | 201 F'05 | lectures | news | help
If your program seg faults on any UNIX system, then your code is buggy !!! It is never the compiler that's at fault. It's always your code.
Here is the code :
Because head was not NULL when we began the list. head held an address that was okay for us to use, which contained some garbage. Since we were always inserting at the end of the list, our list building just continued from there.
Could we have used a debugger to find this error. Sure. Just inspect all of the values of the variables, including the pointers. We'd have seen right away that head was not NULL, 0.
What was going on with the variable fracSum ? Here's a picture of what the memory might have looked like that held main's variables (values shown in hex).
With fracSum declared, head contains a garbage value that just happens to be an address that we are allowed to access. Even though there is no seg fault, our list has garbage in it.
With the declaration of fracSum removed, head contains a garbage value that happens to be an address that we are not allowed to access, so we get a segmentation fault.
I've seen programs that seg fault, but after adding a printf statement as a probe, the program runs. Removing the printf statement causes it to dump again. Changes that you make to your program can cause your variables to be stored at different addresses than before, hence containing different garbage.