Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ object created with new, destroyed with free(); How bad is this?

I am working on modifying a relatively large C++ program, where unfortunately it is not always clear whether someone before me used C or C++ syntax (this is in the electrical engineering department at a university, and we EEs are always tempted to use C for everything, and unfortunately in this case, people can actually get away with it).

However, if someone creates an object:

Packet* thePacket = new Packet();

Does it matter whether it is destroyed with delete thePacket; or free(thePacket); ?

I realize that delete calls the destructor while free() does not, but Packet does not have a destructor. I am having a terrible time stuck in a memory management swamp here and I'm thinking this may be one of the many problems.

like image 421
Dmitri Avatar asked Oct 31 '10 01:10

Dmitri


People also ask

How is free keyword different from Delete?

free() is a C library function that can also be used in C++, while “delete” is a C++ keyword. free() frees memory but doesn't call Destructor of a class whereas “delete” frees the memory and also calls the Destructor of the class.

How do you destroy an object in CPP?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.

What does delete [] do in C++?

The delete [] operator deallocates memory and calls destructors for an array of objects created with new [] . Using delete on a pointer returned by new [] or delete [] on a pointer returned by new results in undefined behavior.


1 Answers

Yes it does matter.

For memory obtained using new you must use delete.

For memory obtained using malloc you must use free.

new and malloc may use different data structures internally to keep track of what and where it has allocated memory. So in order to free memory, you have to call that corresponding function that knows about those data structures. It is however generally a bad idea to mix these two types of memory allocation in a piece of code.

like image 93
srean Avatar answered Sep 30 '22 10:09

srean