Dangling pointer and Memory leaks

Dangling pointers:

Dangling pointers are the pointers that are not pointing to a memory that does not exist, that is memory that is deallocated(invalid memory location).

It refers to something on the stack but nothing on the heap.

#include <stdio.h>              

int *fun()                      
{                                 
  int x = 5;                       
  x++;                           
  return &x;                      
}                                
                                 
int main()
{
   int * ret =fun();
   printf("\n Value is %d",*ret);
   return 0;
}

Output:

Some compilers may give the output as 6 while some may throw a warning:

main.c:7:10: warning: function returns address of local variable [-Wreturn-local-addr]
   return &x;
          ^~

Even though the value is 6 and there is no error, in the future if some other entity gets the same address and so the value of ret will be overwritten. Thus there will be inconsistency and loss of data.

This problem can be solved by making variable ‘x’ as static

Memory leak:

This refers to memory that is allocated is not freed leading to wastage of memory. There is something wrong with memory management.

It’s something on heap but nothing on the stack.

#include <stdio.h>

int main()
{
  char *ptr = malloc(8);
  ptr = "techaccess";
  
  return 0;
}

Once the main() reaches the end of the block, the variable on the stack that is ‘ptr’ goes out of scope but the memory allocated with malloc() is not freed, leading to memory wastage.

Relevant Posts:



Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: