Memory Management in C++: new and delete
Introduction
In my blog about C language, there is also an article about dynamic memory management. If you are interested, you can check it out: C Language - Dynamic Memory Management.
You should be familiar with this diagram:

If you have read my previous blog on Linux process virtual address space, you'll be more comfortable with this. Before I learned Linux, this area was fuzzy; after learning it, I felt a step up.
Warm-up Questions
If you think you are solid with pointers, try these questions:
int globalVar = 1;
static int staticGlobalVar = 1;
void Test()
{
static int staticVar = 1;
int localVar = 1;
int num1[10] = { 1, 2, 3, 4 };
char char2[] = "abcd";
const char* pChar3 = "abcd";
int* ptr1 = (int*)malloc(sizeof(int) * 4);
int* ptr2 = (int*)calloc(4, sizeof(int));
int* ptr3 = (int*)realloc(ptr2, sizeof(int) * 4);
free(ptr1);
free(ptr3);
}
Multiple choice: Options: A. stack B. heap C. data segment (static area) D. code segment (constant area)
- Where is
globalVar? ____ - Where is
staticGlobalVar? ____ - Where is
staticVar? ____ - Where is
localVar? ____ - Where is
num1? ____ - Where is
char2? ____ - Where is
*char2? ____ - Where is
pChar3? ____ - Where is
*pChar3? ____ - Where is
ptr1? ____ - Where is
*ptr1? ____
Fill in the blanks:
- sizeof(num1) = ____;
- sizeof(char2) = ____; strlen(char2) = ____;
- sizeof(pChar3) = ____; strlen(pChar3) = ____;
- sizeof(ptr1) = ____;
Answers:

Explanation:

- Stack (call stack) – non-static local variables, function parameters, return values, etc. Stack grows downward.
- Heap – dynamic memory allocation during program run. Heap grows upward.
- Data segment – stores global and static data.
- Code segment – executable code / read-only constants.
If you didn't get many correct and still don't understand after the diagram, I suggest you study pointers more thoroughly.
C-Style Dynamic Memory Management
A quick reminder:
malloc/calloc/realloc/freemallocallocates uninitialized memory,callocallocates and initializes to zero,reallocresizes existing allocation.
Consider this example:
void Test()
{
int* p1 = (int*)malloc(sizeof(int));
free(p1);
// 1. What is the difference between malloc/calloc/realloc?
int* p2 = (int*)calloc(4, sizeof(int));
int* p3 = (int*)realloc(p2, sizeof(int) * 10);
// 2. Do we need to free(p2) here?
free(p3);
}
If you're unsure, refer to the initial blog I mentioned.
C++ Memory Management
C-style memory management can still be used in C++, but it has limitations and is cumbersome. Therefore, C++ introduces its own memory management via new and delete operators.
new/delete for Built-in Types
int main()
{
// C style: allocate a single int
int* p1 = (int*)malloc(sizeof(int));
if (p1 == nullptr)
{
perror("malloc fail");
exit(-1);
}
// C++ style: allocate a single int
int* p2 = new int;
// C style: allocate an array of 4 ints
int* p3 = (int*)malloc(sizeof(int) * 4);
if (p3 == nullptr)
{
perror("malloc fail");
exit(-1);
}
// C++ style: allocate an array of 4 ints
int* p4 = new int[4];
// C style: free
free(p1);
// C++ style: delete
delete p2;
// C style: free
free(p3);
// C++ style: delete[]
delete[] p4;
return 0;
}
As you can see, C++ is more convenient. If we also want to initialize the data, C++ is simpler:

Note: new[] with {} initialization is supported in C++11 and later, not in C++98.
For built-in types, new/delete and malloc/free are essentially the same, only differing in syntax. But for custom types, they are different.
new/delete for Custom Types
Consider a class A:
class A
{
public:
A(int a = 0)
: _a(a)
{
std::cout << "A():" << this << std::endl;
}
~A()
{
std::cout << "~A():" << this << std::endl;
}
private:
int _a;
};

When using new, the default constructor is automatically called to initialize the object. When using delete, the destructor is called first to clean up resources, then memory is freed.

But malloc and free do not call constructors or destructors.
Conclusion: new/delete are designed for custom types. They allocate memory on the heap and also call constructors/destructors for initialization and cleanup.
new and delete can also allocate arrays for built-in types:

Extra elements are zero-initialized.

You can also write initialization like this:

Note: Always match new/delete and new[]/delete[]. Mismatching can cause problems, especially for custom types.
Example of mismatch:

new Allocation Failure
When new fails to allocate memory, it throws an exception. We will cover exceptions later in inheritance and polymorphism. For now, just remember that unlike malloc, you don't need to check the pointer after new.
operator new and operator delete Functions
new and delete are operators that users use for dynamic memory allocation and deallocation. operator new and operator delete are global functions provided by the system. new calls operator new to allocate space, and delete calls operator delete to free space.
Let's look at the disassembly:

operator new: This function actually allocates space viamalloc. Ifmallocsucceeds, it returns directly; if it fails, it tries the user-defined new-handler (if set), otherwise throwsstd::bad_alloc.
About
operator new:
About
operator delete:
_free_dbg is essentially free:

From the above, we see that operator new uses malloc internal, and operator delete uses free.
Implementation Principles of new and delete
Built-in Types
For built-in types, new and malloc are similar except that new throws exceptions on failure, while malloc returns NULL. Similarly, delete and free are similar, but delete/delete[] are for single objects and arrays respectively.
Custom Types
new principle:
- Call
operator newto allocate space.- Call the constructor on the allocated space to initialize the object.
delete principle:
- Call the destructor on the space to clean up resources.
- Call
operator deleteto free the space.
new T[N] principle:
- Call
operator new[]which internally callsoperator newto allocate space for N objects.- Call the constructor N times on the allocated space.
delete[] principle:
- Call the destructor N times on the objects to clean up resources.
- Call
operator delete[]which internally callsoperator deleteto free space.
Placement new
Placement new is used to call a constructor on an already allocated raw memory to initialize an object.
Syntax:
new (place_address) typeornew (place_address) type(initializer-list)
place_address must be a pointer, and initializer-list is the initialization list for the type.
When we allocate memory for a custom type using malloc, the object is not initialized. Since constructors may be private, we cannot call them directly. Placement new allows us to initialize the object.
Example:

Or like this:

This scenario appears limited, but it's useful in certain contexts. For now, just understand the syntax.
Interview Question: Differences between malloc/free and new/delete
Common points: Both allocate memory from the heap and require manual deallocation by the user.
Differences:
malloc/freeare functions;new/deleteare operators.mallocallocated memory is uninitialized;newcan initialize.mallocrequires manual calculation of size and passing it;newonly needs the type, and for arrays, specify the count in[].mallocreturnsvoid*, requiring a cast;newreturns the correct type pointer.mallocreturnsNULLon failure, requiring null-check;newthrows an exception.- For custom types,
malloc/freeonly allocate/deallocate memory;new/deletecall constructors and destructors.
That's all for now.

