Pointer initialisation gives segmentation fault

CASE .1

int *a; /* pointer variable declaration */

int b; /* actual variable declaration */

*a=11;//Not valid means you are not owner of the address where a now pointing it is unknown and accessing this will segfault/

a=&b;/* store address of b in pointer variable*/

This is going to be segmentation fault because the address you are using is not a valid address and there you are storing 11 which is illegal.

                               b
      +-------+            +--------+
      |       +            |   11   |
      |Unknown|            |        |
      +---+---+            +---+----+
          |                    |
          |                    |
          +                    +
          a                    a
CASE .2

int *a; /* pointer variable declaration */

int b; /* actual variable declaration */

a=&b;/* store address of b in pointer variable*/

*a=11;

Now its working fine because the address of b is valid an there you are storing 11 which is legal.

Also above cases are not correct way of pointer declaration

  int *a  = NUll;
  a = malloc(sizeof(int));
  *a=5;
  free(a);//must

or

 int *a  = NUll;
 int b;
 a = &b;
 *a=5;

This will remove segmentation fault many times which is hard to find .

Leave a Comment