Is it a memory leak?

I am new to C ++ and I just found out about dynamic memory and memory leaks.

From what I understand, by creating a pointer ( int *ptr = new int ) and then changing the address that it points to, the old address still exists / is allocated. (please correct me if I'm the three of us).

so I thought about this:

 int *ptr; ptr = new int; 

The first ptr is filled with a random (or not?) Address, then I change it, so does the old one remain? if I try this code:

 int *ptr; cout << ptr << endl ; ptr = new int; cout << ptr << endl ; 

I get:

 0x401a4e 0x6d2d20 

Does this mean that 0x401a4e is part of a memory leak? Or is it freed when ptr goes into dynamic memory? How it works?

+4
source share
4 answers

The first line ( int *ptr; ) does not allocate any dynamic memory, so there is no memory leak. The value you see is not initialized. This is not a valid pointer. You must not delete the pointer before assigning it a value. This will be undefined behavior.

+9
source

You need to understand that memory leaks do not concern pointers (in fact: never - even if many people will require something else). The entire business with pointers is simply misleading.

They are associated with a mismatch in the allocation and release of dynamic memory.

Each selection through new must match one selection through delete . The same goes for malloc and free and new[] and delete[] (and other proposed 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 little (in most cases: no ) manual allocation of dynamic memory. This way you cannot have leaks. Basically. This is very good, so do it. Instead of manually allocating dynamic memory, you can use standard containers and smart pointers that handle memory management for you.

+15
source

In C / C ++, memory will not be automatically released. So yes, if you do this:

  YourType* ptr = new YourType(); ptr = new YourType(); 

you will have a memory leak.

But in your case, you do not have a memory leak, because the first value is not a valid memory address. This is an uninitialized pointer.

+2
source

No, this is not a memory leak. The difference is that when you say " new int ", you tell C ++ to reserve a block of memory to store int ; if you lose the pointer to this reserved block, then it cannot be restored and cannot be freed, and therefore it is a leak because it can never be reused.

Simply storing some bits in a pointer variable does not do any magic; they are just bits. It allocates memory with new , which may cause you problems. After you have reserved a block, you must be sure that you will not lose it.

0
source

All Articles