Home > Back-end >  Do I need to delete pointer in stack, which is created in heap?
Do I need to delete pointer in stack, which is created in heap?

Time:03-18

int *createInt()
{
   int *a = new int;
   return a;
}

int main()
{
   int *x = createInt();
   *x = 10;
   cout << *x << '\n';
   delete x; // do I need this?
   return 0;
}

DO I need delete x? If i don't, will it cause a memory leak problem?

CodePudding user response:

You appear confused about the distinction between a pointer and the pointed at object. a and x are pointers. Think of a piece of paper with a party address written on it.

int *a = new int; allocates a new object on the heap and assigns the address to the pointer a. This is like starting a party at a house, and then writing the address on a paper named a.

return a; returns the pointer to the caller. This is like handing the address-paper to the person that told you to start a party.

*x = 10; accesses the object, and modifies it. This is like going to the address on the paper, and passing around silly hats, you've changed it to a costume party.

delete x; // do I need this? Yes, you need to delete the object that you allocated. This says "end the party at the address on this paper".


Other questions:

what if I don't delete memory? Then the party continues forever, and nobody else can party at that address ever again because the first party is still going.

what if I delete the memory twice? Ending a party twice makes no sense. Nothing might happen. Or it might burn down. Or it might be different each time.

what if I use the pointer after deleting it? Going to a party that ended makes no sense. Maybe nothing happens. Or maybe someone replaced the house with a Military base, and you're trespassing and get arrested. Or it might be different each time.

what if I reassign the pointer without deleting? If you erase the paper and write a new address on it, that doesn't do anything to the party. Except that you probably won't ever find it again, and the party continues forever.

I was told that members of classes are destroyed when the class is destroyed. Does that delete the object? No, burning the piece of paper with the address on it doesn't end the party.

CodePudding user response:

This statement

delete x;

does not delete the pointer x itself. It deletes the dynamically allocated memory pointed to by the pointer x

int *a = new int;

//...

int *x = createInt();

After this statement

delete x;

the pointer x will be alive but will have an invalid value. As the pointer itself has automatic storage duration then it will be destroyed automatically after the end of the block scope where it is defined.

You should always delete dynamically allocated memory to avoid a memory leak.

  • Related