I am new to c++ and I just learned about dynamic memory and memory leaks.
From what I understand, when creating a pointer(int *ptr = new int
), and then changing the address that he is pointing, the old address still exist/allocated.
(please correct me if I am wronge).
so I thought about this:
int *ptr;
ptr = new int;
first ptr is fill with random(or not?) address, then I change it, so the old one stays? if I try this code:
int *ptr;
cout << ptr << endl ;
ptr = new int;
cout << ptr << endl ;
I get:
0x401a4e
0x6d2d20
Does it mean that 0x401a4e is part of a memory leak? Or is it released when ptr moves to dynamic memory? How does it work?
You need to understand that memory leaks are not about pointers (really: never – even though a lot of people will claim something different). The whole business with pointers is just misleading.
They are about a mismatch in dynamic memory allocations and deallocations.
Every allocation via new
must be matched with exactly one deallocation via delete
. Same for malloc
and free
and new[]
and delete[]
(and other conceivable dynamic resource allocation functions).
int* x; // Not a memory leak: no dynamic allocation
new int; // Memory leak: we acquired a value via `new` and lost it.
int* y = new int;
int* z = y;
delete y; // Not a memory leak any more: we freed the memory.
delete z; // Oooh, bad: we deleted a value twice. The horror.
Modern C++ code uses very few (in most cases: no) manual dynamic memory allocations. That way, you cannot have leaks. In principle. This is very good, so do it. Instead of manual dynamic memory allocations, you can make use of standard containers and smart pointers which handle the memory management for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With