Difference between dangling pointer and memory leak

后端 未结 8 1969
既然无缘
既然无缘 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:18

    A dangling pointer points to memory that has already been freed. The storage is no longer allocated. Trying to access it might cause a Segmentation fault.

    Common way to end up with a dangling pointer:

    char *func()
    {
       char str[10];
       strcpy(str, "Hello!");
       return str; 
    }
    //returned pointer points to str which has gone out of scope. 
    

    You are returning an address which was a local variable, which would have gone out of scope by the time control was returned to the calling function. (Undefined behaviour)

    Another common dangling pointer example is an access of a memory location via pointer, after free has been explicitly called on that memory.

    int *c = malloc(sizeof(int));
    free(c);
    *c = 3; //writing to freed location!
    

    A memory leak is memory which hasn't been freed, there is no way to access (or free it) now, as there are no ways to get to it anymore. (E.g. a pointer which was the only reference to a memory location dynamically allocated (and not freed) which points somewhere else now.)

    void func(){
        char *ch = malloc(10);
    }
    //ch not valid outside, no way to access malloc-ed memory
    

    Char-ptr ch is a local variable that goes out of scope at the end of the function, leaking the dynamically allocated 10 bytes.

提交回复
热议问题