Wednesday, October 10, 2012

Stray Pointer

Stray pointer: 

Stray pointers are some times very dangerous because with stray pointer your program can crash. As we can guess from the name "stray" stray pointers are really stray having no home. Let me clear you with an example.

Suppose in your program you have dynamically allocated some memory (Using malloc( )) and then after using that memory you freed that memory (Using free( )).

Now stray pointer will be created if you will access the deleted memory or you will assign some value at that address.

Example with C program:

1: #include<stdio.h>  
2: void main(void)  
3:{  
4:  int i;  
5:  int *ptr;  
6:  ptr = (int *)malloc(sizeof(int) * 5); // Dynamically allocating 20 Bytes of memory  
7:  for (i = 0 ; i < 5 ; i++)  
8:  {  
9:      *(ptr+i) = i;            // Assing values  
10: }  
11: for (i = 0 ; i < 5 ; i++)  
12: {  
13:     printf("value = %d\n",*(ptr+i));  // printing values on console  
14: }  
15: free(ptr);               // Freeing memory   
16: for (i = 0 ; i < 5 ; i++)   
17: {  
18:     *(ptr+i) = i;            //uh oh, This was deleted!!  
19: }  
20:}  

Explanation: 

In the 6th line we have dynamically allocated 20 Bytes (int is of 4 bytes) of memory.

Now pointer "ptr" has the base address of allocated 20 bytes. 
From line 7 to 10 we are assigning values 
From line 11 to 14 we are printing assigned value at console 
In 15th line we freed the memory by calling free function 
From line 16 to 19 That's the main problem here we are assigning the value which is unknown. We are using that memory which does not belong to us.

2 comments:

je-so said...

Hi !

I use some trick to prevent the above error.

For every object type I write the following pair of functions:

static int new_type(type_t ** obj)
{
*obj = malloc(sizeof(type_t)) ;
return (*obj) ? 0 : ENOMEM ;
}

static int free_type(type_t ** obj)
{
free(*obj) ;
*obj = 0 ; // clear pointer !!!
return 0 ;
}

Unknown said...

Hi jo-so!

I like the simplicity of your trick. Great use of functions. In first function you are allocating memory and in second call you are freeing allocated memory.