A segmentation fault is caused because of bad coding practices. It is also called as sig failts. This kind of faults prevent the program or application to not continue further with execution.
Segmentation fault happens, If a application if tries to access a memory location which it should not.
Cause of segfaults
- If a buffer over flow happens.
- While dereferencing a NULL pointer.
- Using uninitialized pointer.
- Accessing a memory, that we should not (not belonging to the program)
Click on more to continue reading on detecting location of segfault and practices to avoid segfaults.
Detecting segment fault in program using gdb
Lets take the below program as example. Lets name the file as seg1.c
#include <stdio.h> int main() { char *string = NULL; *string = 'a'; return 0; }
This program creates a segment fault, the reason is the memory is not allocated but used.
To find the location of segmentation fault, compile the program with -g option.
$ gcc -g seg1.c
Now lets use gdb to debug the program
$ gdb a.out
You can see gdb pointing to line 8 where the segmentation fault has happened.
Good practice to avoid segment fault
- To avoid using pointers without allocating, you can have the variable name start with ‘p’ eg., pszSomeString, piInteger. This will make you cautious saying you are working with a pointer variable.
eg.,
#include <stdio.h> int main() { char *pszString = NULL; int *piInterger = NULL; .... }
- Have wrapper to string functions like strcmp, strstr, strcat, strlen, strcpy …
- Have a macro check if memory of the variable is allocated before deallocate. Also initialize the pointer variables to NULL during initialization
eg.,
#include <stdio.h> #include <stdlib.h> /* Macro to check memory allocated before freeing */ #define MEMFREE(X) { if(X) { free(X); X=NULL; } } int main() { char *szString = NULL; szString = (char*) malloc(100); /* Check if memory is allocated */ if(!szString) { /* Code to handle failed memory allocation */ } MEMFREE(szString); return 0; }
- Check if the pointer is allocated before using the pointer variable. See example above
Related posts:
