Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Memory Management in C++: new and delete

Tech Nov 14 15

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: Memory Layout

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: Answers Answers continued

Explanation: Memory Regions

  1. Stack (call stack) – non-static local variables, function parameters, return values, etc. Stack grows downward.
  2. Heap – dynamic memory allocation during program run. Heap grows upward.
  3. Data segment – stores global and static data.
  4. 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 / free
  • malloc allocates uninitialized memory, calloc allocates and initializes to zero, realloc resizes 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: Initialization

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;
};

new/delete behavior

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.

Comparison

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: Array allocation

Extra elements are zero-initialized. Zero initialization

You can also write initialization like this: Initialization syntax Another example

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

Example of mismatch: Mismatch example

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: Disassembly

operator new: This function actually allocates space via malloc. If malloc succeeds, it returns directly; if it fails, it tries the user-defined new-handler (if set), otherwise throws std::bad_alloc.

About operator new: operator new source

About operator delete: operator delete source

_free_dbg is essentially free: free implementation

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:

  1. Call operator new to allocate space.
  2. Call the constructor on the allocated space to initialize the object.

delete principle:

  1. Call the destructor on the space to clean up resources.
  2. Call operator delete to free the space.

new T[N] principle:

  1. Call operator new[] which internally calls operator new to allocate space for N objects.
  2. Call the constructor N times on the allocated space.

delete[] principle:

  1. Call the destructor N times on the objects to clean up resources.
  2. Call operator delete[] which internally calls operator delete to 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) type or new (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: Placement new example 1

Or like this: Placement new example 2

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:

  1. malloc/free are functions; new/delete are operators.
  2. malloc allocated memory is uninitialized; new can initialize.
  3. malloc requires manual calculation of size and passing it; new only needs the type, and for arrays, specify the count in [].
  4. malloc returns void*, requiring a cast; new returns the correct type pointer.
  5. malloc returns NULL on failure, requiring null-check; new throws an exception.
  6. For custom types, malloc/free only allocate/deallocate memory; new/delete call constructors and destructors.

That's all for now.

Tags: C++

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.