The difference between malloc and new

The difference between malloc and new is subtle, but important if you are mixing C and C++. malloc will allocate the memory needed for your object. new will allocate your memory and call your constructor as well, executing any code in it.

The same difference applies to free and delete.

Here’s a code example.

#include <cstdlib>
#include <iostream>

struct MyClass {
    
int property = 0;
 
MyClass() {
    property = 10;
}

~MyClass() {
    std::cout << "Object destructor called" << std::endl;
}
 
};
 
int main(int argc, char** argv) {
   MyClass *my_class_malloc = (MyClass*) malloc(sizeof(MyClass)); // just allocated memory
   std::cout << "Property : " << my_class_malloc->property << std::endl;
   MyClass *my_class_new = new MyClass(); // calls constructor and sets to 10
   std::cout << "Property : " << my_class_new->property << std::endl;
   
   std::cout << "Calling free..." << std::endl;
   free(my_class_malloc);
   
   std::cout << "Calling delete..." << std::endl;
   delete(my_class_new);
}