I would like to discuss, how to fix segmentation faults in C++ coding.
- compile and link the code with -g option so that you can use gdb
- gdb ./a.out
- gdb> r
- gdb> backtrace
The above will give you which line caused segmentation fault. The following steps generally helps one to avoid/fix them.
- Before you do any testing, delete all your object files and regenerate them and see if the segmentation fault still exists. On some situations, it will go away because you would have linked with a wrong kind of object file.
- When you need read only access to a vector, use the at() method instead of [ ]
- If a function is declared to return something, do return that object. I have found that during development of the method, I may forget to return the ‘return object’ as it may not be ready yet (i am developing my method only) and when I do a test run, I get a segmentation violation. I have spent hours in fixing such segmentation violations, because I forget that I have not returned what I declared to return. It is surprising that compiler (g++) does not catch this error
- Use
constwherever possible. ie as arguments to function if they do not change andconstafter the declaration of arguments of the function if the function will not change the state of the object. - If you want to watch the contents of STL containers, use the STL support for gdb link from the gdb home page
Recent Comments