Hi I was just wondering if I create a pointer using the new operator and then I call the new operator on that same pointer later on would that overwrite the existing pointer so that I do not waste memory on the heap or do I have to delete it then use the new operator again.

EG:

ClassA* objA = new ClassA();
.
.
objA = new ClassA();

OR

ClassA* objA = new ClassA();
.
.
delete objA;
objA = new ClassA();

Thank You in advance

Recommended Answers

All 8 Replies

You have to, at least, save the original pointer value somewhere so that you can delete and free up the memory...otherwise you create a memory leak.

So lets say I store all pointers within an array and then I delete them one by one at the end would that free up all the memory that I have allocated????

EG:

for(int i = 0; i < 50; i++)
{
	object = new Planet();
	objectVector.push_back(object);
}
.
.
.
.
.
for each(GameObject* object in objectVector)
	SAFE_DELETE(object);

The general rule is...If you call new x times then you must/should call delete x times.

ok I see nice one thanks I guess what I just wanted to make sure of is if I create 2 pointers and i assign one to the other and I delete one of them, would that de-allocate both?

EG:

ClassA *objA = new ClassA(), *objB = objA;

delete objB;

would this delete both????

Well number one...you don't deallocate both since we're only talking about one chunk of dynamic memory.

In your above example you should delete one pointer to the memory chunk and then set both pointers to NULL.

What would happen if I dont set the other to NULL? would that still be taking up memory on the heap??? or have I already de-allocated that chunk of dynamic memory???

thanks in advance

Remember that general rule...Call delete the same amount of times that you call new.

Thanks alot mate you've really helped me out

thumbs up :d

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.