Difference between dangling pointer and memory leak

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

    A dangling pointer is one that has a value (not NULL) which refers to some memory which is not valid for the type of object you expect. For example if you set a pointer to an object then overwrote that memory with something else unrelated or freed the memory if it was dynamically allocated.

    A memory leak is when you dynamically allocate memory from the heap but never free it, possibly because you lost all references to it.

    They are related in that they are both situations relating to mismanaged pointers, especially regarding dynamically allocated memory. In one situation (dangling pointer) you have likely freed the memory but tried to reference it afterwards; in the other (memory leak), you have forgotten to free the memory entirely!

提交回复
热议问题