Pointers are like sharp knives in C-Programming which are having tremendous power. Pointers, when used properly reduces the complexity of the programs to a great extent. But, on the counterpart when not used properly results in adverse effects, in an worst case, it may crash the system. In this blog, I am mainly focusing on two different situations where Dangling pointers in C programming be avoid it in a simple way.
code snippets provided here is tested with GCC compiler [ gcc version 4.7.3 ] running under Linux environment.
Dangling pointers in C programming :Simply, the pointers not pointing to the valid memory location ( Object ).
To Explain with, I am considering the two different cases , giving rise to Dangling Pointers.
Case :1. When a function returns address of the auto-variables.
Case :2. In dynamic memory allocation, using the block of memory which is already freed.
Case 1: Function returning address of the auto-variables.
Consider the simple code given below in fig 1,
|Fig 1: Code returning the address of the local / auto variables.|
When we run the above program in gcc compiler we get the warning as given in the Fig 2,
|Fig 2: Compiler generating warning.|
But, What is wrong when address of the auto/local variables are returned ? Let us see this,
1. We know that whenever , there is a function call, new stack frame will be created automatically.
2. When the control returns from the function call, all the memory allocated for that function will be freed automatically.
3. In our example program, we are returning the address of the auto variable and collecting this in the ‘int_ptr ‘pointer in the main function. So, int_ptr is still pointing to the memory which is freed as per the point no.2 .
4. One can observe allocation & de-allocation of stack frame(Let us called this as fun frame) for the fun() in the Fig 3 given below,
5. Now, int_ptr becomes ‘Dangling’. De-referencing this pointer results in ‘Unexpected output’
6. So, always take extra care while playing with pointers & local variables.
Case 2. In dynamic memory allocation, using the block of memory which is already freed.
Consider the below sample code,
|Fig 4: Code snippet, showing re-using of block_ptr.|
Explanation: For the code snippet shown in Fig 4
Line 5:Memory allocation by malloc().
Line 9:Memory allocated is freed by free() manually.
In case 1: Memory is freed automatically.
In case 2: Memory is freed manually. This is the one of key difference between stack & heap.
Line 13:Re-using the pointer, which is still pointing to the memory which is already freed. In our example block_ptr is now called as “Dangling Pointer”
But, In case 2 pointer becoming dangling can be avoided by initializing it to ‘NULL’ immediately after freeing it.
block_ptr = NULL;
Dangling pointers are very harmful and results in adverse effects in the embedded systems programming. So. It should be “STRICTLY” avoided.