How to avoid Segmentation Fault

1. Proper pointer initialization

One common way is to assign the pointer an address to a previously defined variable. For example:

int * ptr;
int variable;
sptr = &variable;

Or, equivalently,

int variable;
int *ptr = &variable;

Other common ways include assigning the pointer the address of memory allocated with matrix, vector, calloc, or malloc or other equivalent allocation functions. Remember, a pointer must be initialized to a value (i.e., assigned a value by appearing on the left-hand-side of an assignment statement) BEFORE you attempt to access it!

2. Minimizing the use of pointer variables

Also, many times a function requires that an address (corresponding to a parameter of pointer type) be sent to it as an argument (as is true of many of the Numerical Recipes in C functions). The standard function scanf is an example of such a function.
In these cases, it is usually best to simply declare a variable of the correct type before calling the function and just sending the address of the variable to the function. In fact, that is what is intended in the vast majority of these cases. And, that’s how you usually scanf

double x_initial;        /* initial guess */
scanf("%lf",&x_initial); /* Read the initial guess. */

For example, see how ‘idum’ is used below:

long idum = -1; /* initialize idum to be a negative integer */
/* generate a random number from the normal distn.*/
x = normal(&idum,average,stddev);

The function normal expects an address to a variable of type long. That’s what we send it without explicitly using a pointer variable in the calling routine.

3. Troubleshooting the problem

Check EVERY place in your program that uses pointers, subscripts an array, or uses the address operator (&) and the dereferencing operator (*). Each is a candidate for being the cause of a segmentation violation. Make sure that you understand the use of pointers and the related operators.
If the program uses many pointers and has many occurrences of & and *, then add some printf statements to pinpoint the place at which the program causes the error and investigate the pointers and variables involved in that statement.
Remember that printf statements for debugging purposes should have a new-line character (\n) at the end of their format control strings to force flushing of the print buffer.