Scott
Scott

Reputation: 5263

Using free inside the destructor of an object freed with delete

I have an object that I'm freeing with delete, and it has a char* that's being freed with free in its destructor. The reason I'm using free is because I used strdup and malloc in creating the char pointers. The reason I'm using malloc is because I used strdup to begin with in most code paths. Would this scenario cause memory corruption?

Upvotes: 2

Views: 1683

Answers (4)

Sam
Sam

Reputation: 7398

I figured out what was wrong. I was passing my object as a copy through a method, and it kept the char* across; when the function exited, that temporary object got deleted, freeing the char*. Now I need the char* after the method exited, but that's gone now. Two *'s and minus one fixed it.

Upvotes: 0

sharptooth
sharptooth

Reputation: 170509

Your implementation is correct. You use free() to release memory allocated with malloc() (or strdup()) and this is exactly what to do.

The requirement is that you release memory with a primitive matching the one used to allocate that memory. And this requirement is met in your implementation.

Upvotes: 1

CB Bailey
CB Bailey

Reputation: 792657

What you are doing is correct. A class that has been newed should be deallocated with delete, but if it owns memory that was allocated with malloc (either directly or indirectly) then it should deallocate that memory with free.

Upvotes: 2

Naveen
Naveen

Reputation: 73473

No, if you match calls properly i.e. free() for memory allocated with malloc() and delete for memory allocated with new, it will work fine.

Upvotes: 5

Related Questions