Domanda

I am learning C++ in an online class, currently discussing pointers and memory leaks.

In the course it was told that when a function body ends all local variables are destroyed (in reverse order to which they were declared).

What i'm trying to understand is whether this code leaks memory or not:

void function()
{
    TestClass *p = new TestClass();
}

As it seems, it does, but i am not sure why the pointer "p" is not being dereferenced to its heap address and the data there is deleted once the function scope exits.

È stato utile?

Soluzione

Definitely it will leak memory. when a function body ends all local variables are destroyed indicates to the variables that are created in stack, not heap. If you allocate memory in heap, you have to release it when done.

Another thing is your concept about dereference is wrong. Dereference means using the object pointed by a pointer, not freeing the memory of the pointer, which is called Deallocation

Altri suggerimenti

The pointer itself will be destroyed as it is allocated in stack, but the data which p points to will leak. If you write

TestClass tc;
TestClass *p = &tc;

then all the objects will be created in stack and destroyed, but using new forces to use the memory from heap. You have to use delete to release it.

new is used to allocate memory for a C++ class object in heap, the object's constructor is called after the memory is allocated.

The delete operator must be used to deallocate the memory allocated with the new operator, otherwise there is a memory leak.

delete *p;

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top