Difference between dangling pointer and memory leak

后端 未结 8 1971
既然无缘
既然无缘 2020-12-12 08:44

I don\'t understand the difference between a dangling pointer and a memory leak. How are these two terms related?

相关标签:
8条回答
  • 2020-12-12 09:20

    A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer. There are three different ways where Pointer acts as dangling pointer.

    1. De-allocation of memory
    2. Function Call
    3. Variable goes out of scope

    —— from https://www.geeksforgeeks.org/dangling-void-null-wild-pointers/

    0 讨论(0)
  • 2020-12-12 09:21

    Dangling Pointer

    If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer problem.

    #include<stdio.h>
    
      int *call();
    
      void main(){
    
          int *ptr;
          ptr=call();
    
          fflush(stdin);
          printf("%d",*ptr);
    
       }
    
     int * call(){
    
       int x=25;
       ++x;
       return &x;
     }
    

    Output: Garbage value

    Note: In some compiler you may get warning message returning address of local variable or temporary

    Explanation: variable x is local variable. Its scope and lifetime is within the function call hence after returning address of x variable x became dead and pointer is still pointing ptr is still pointing to that location.

    Solution of this problem: Make the variable x is as static variable. In other word we can say a pointer whose pointing object has been deleted is called dangling pointer.

    Memory Leak

    In computer science, a memory leak occurs when a computer program incorrectly manages memory allocations. As per simple we have allocated the memory and not Free other language term say not release it call memory leak it is fatal to application and unexpected crash.

    0 讨论(0)
提交回复
热议问题