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.
Post a Comment