memory leak

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mar11
    New Member
    • Sep 2009
    • 38

    memory leak

    Hi all,

    I am a bit confused about the real cause of memory leak in this case:

    int a(4);
    int Pointer_1*;
    int Pointer_2* = &a

    Pointer_1 = new int;

    Pointer_1 = Pointer_2;

    I know that the Pointer_1 is in this way overwritten and the pointer to the allocated int is lost. But i still can't understand why it leads to mem lack if the pointer to the allocated object is lost?

    Thanks in advance
  • hype261
    New Member
    • Apr 2010
    • 207

    #2
    In C++ any time you allocate on the heap via the new keyword you are responsible for managing that memory. All that the variable Pointer_1 contains is the address of the int you allocated on the heap

    When you execute the following line of code Pointer_1 = Pointer_2 you have just lost the ability to know where on the heap that memory is allocated and since you are responsible for deleting it, you can't any more. The memory just sits idle doing nothing. That is why it is a memory leak.

    Comment

    Working...