Posted by: sureshamrita | August 19, 2010

Segmentation fault in C++

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 const wherever possible. ie as arguments to function if they do not change and const after 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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: