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?
The first line (
int *ptr;) does not allocate any dynamic memory so there is no memory leak. The value you see is uninitialized. It is not a valid pointer. You should not delete the pointer before assigning a value to it. Doing so would be undefined behaviour.