As pointers are little different from any other variable, and still considered as normal variable, it is obvious that we forget that it is a pointer. Hence we may end up in some common mistakes while creating pointer variables.
Not assigning Memory
Whenever we create a pointer variable, it is very much essential to assign memory to them. Since it is a pointer, compiler will expect some memory address while compiling it. Sometimes compiler will assign some memory from the system to it, which are not intended for program or pointers. Hence using such memory for the pointer will crash the system. Sometimes pointer will not be assigned any memory and will be hanging in the system. This is also not expected, as it will create wrong interpretation to the compiler. Hence we need to assign some free memory to it or at least assign NULL to them so that compiler understands that it is not hanging around the system. In addition assigning memory to the pointers will make those memory blocks set for these pointers and will not allow any other pointer / program to use them.
If we do not assign any memory to the pointer variable, compiler will not identify while compiling. Hence we will see error free code. At the run time all the disaster will happen!
Suppose we have declared and assigned value as below: Compiler will not show any error in below case as some random memory address will be allocated to intX while declaring it.
int *intPtrX; // No memory is allocated to the pointer variable * intPtrX = 30; //still value is assigned to it, which may change the value at some illegal location! </code>Hence it is very much necessary to make the pointer to point to correct memory address as below:</pre> <pre><code>int *intPtrX; // No memory is allocated to the pointer variable intPtrX = &intY; // Memory address of intY is allocated to pointer, hence it will point to correct address in the system *intPtrX = 30; // it will change the value on intY now rather than changing some unknown values
int *intPtrX = NULL;
int *intPtrX = malloc(sizeof(int));