How to Avoid Segmentation Fault

◀ General Causes▶ Layout of a Program
Amazon After my having pointed out the common causes of a segmentation fault, it should be easy to see how to avoid it.

First of all, whenever you use an array, make sure you never do anything that will result in the array’s going out of bounds. For example, if you expect the array’s index from user, you should check that it is within the array’s range. Whenever you are using a fixed number as some array’s index make sure it will always be valid.

Secondly, whenever you use free or delete to deallocate memory, always make sure you have used malloc (paired with free) or new (paired with delete) earlier to allocate that piece of memory. Other combinations of allocating memory and deallocating memory are either undefined or forbidden; so steer clear of them.


Also, do NOT free memory twice.

Let me share with you my experience of using delete. I allocate memory for an array, but later depending on the condition in an if block, control goes through different routes. One of them has the corresponding memory deallocated but the other has it deallocated twice, which results in a segmentation fault. It takes a while to debug, but it’d be nice to pay attention to each possible control flow to begin with.

Finally, before you manipulate a pointer, make sure it points to a valid address. Using new is a good idea because it does its best to not give you a segmentation fault no matter how you access data associated with the address pointed to by the pointer.


If you don’t want to use the pointer at the moment, making it point to NULL is not a bad idea.
Each human eye has about 200 eyelashes, each of which has an average life of 3 to 5 months.
◀ General Causes▶ Layout of a Program

fShare
Questions? Let me know!