Difference Between new and malloc C++

1. Introduction

In C++ programming, memory allocation is a fundamental concept. new and malloc() are two different ways to allocate memory dynamically, but they serve different purposes and have different behaviors in C++.

2. Key Points

1. new is an operator in C++ that allocates memory and calls the constructor for object initialization.

2. malloc() is a C library function that allocates memory but does not call constructors.

3. new returns a typed pointer and can be overloaded.

4. malloc() returns a void* pointer and cannot be overloaded.

3. Differences

new malloc()
Allocates memory and calls the constructor. Allocates memory without calling the constructor.
Returns a typed pointer. Returns a void* pointer.
Can throw an exception on failure. Returns NULL on failure.
Can be overloaded. Cannot be overloaded.

4. Example

#include <iostream>
using namespace std;

class MyClass {
public:
    MyClass() {
        cout << "Constructor called\n";
    }
};

int main() {
    // Using new
    MyClass *obj1 = new MyClass;

    // Using malloc
    MyClass *obj2 = (MyClass *)malloc(sizeof(MyClass));

    // Destructor will not be called for obj2
    delete obj1;
    free(obj2);

    return 0;
}

Output:

Constructor called

Explanation:

1. new MyClass allocates memory for obj1 and calls the constructor of MyClass.

2. malloc(sizeof(MyClass)) allocates memory for obj2 but does not call the constructor, hence no output for constructor call.

5. When to use?

- Use new in C++ when you need to allocate memory for objects and require constructors to be called.

- malloc() can still be used for allocating memory without invoking constructors, typically in situations involving compatibility with C code or low-level memory manipulation.

Related C++/CPP Posts:

Difference Between Struct and Class in C++

Difference Between Pointer and Reference in C++

Difference Between null and nullptr in C++

Difference Between Array and Vector in C++

Difference Between const and constexpr in C++

Difference Between List and Vector in C++

Difference Between C and C++

Difference Between Function Overloading and Operator Overloading in C++

Difference Between Array and List in C++

Difference Between a While Loop and a Do-While Loop in C++

Difference Between new and malloc C++

Virtual Function vs Pure Virtual Function in C++

Compile Time Polymorphism vs Runtime Polymorphism in C++

Difference Between Shallow Copy and Deep Copy in C++

Difference Between Stack and Heap in C++

Copy Constructor vs Parameterized Constructor in C++

Comments