views:

119

answers:

3

I'm having a little issue. 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?

Edit: 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.

+4  A: 

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.

Naveen
+2  A: 

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.

Charles Bailey
+1  A: 

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.

sharptooth