Menu
Coddy logo textTech

Dynamic Memory (new/delete)

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 14 of 104.

Now that you understand pointers and references, let's put them to work with dynamic memory allocation. The new and delete operators let you create and destroy objects on the heap at runtime.

Use new to allocate memory and get back a pointer to it:

int* num = new int;        // Allocate single integer
*num = 42;                 // Assign value through pointer

Player* player = new Player("Hero");  // Allocate object

Every new must have a matching delete to free the memory:

delete num;      // Free single object
delete player;   // Calls destructor, then frees memory

For arrays, use new[] and delete[]:

int* scores = new int[5];    // Allocate array of 5 integers
scores[0] = 100;

delete[] scores;             // Free array - note the brackets!

Common mistakes to avoid:

// Memory leak - forgot to delete
int* ptr = new int(10);
ptr = new int(20);    // Lost access to first allocation!

// Dangling pointer - using after delete
delete ptr;
*ptr = 5;             // Undefined behavior!

// Mismatched delete
int* arr = new int[10];
delete arr;           // Wrong! Should be delete[]

After deleting, set pointers to nullptr to avoid accidental reuse. Manual memory management is error-prone, which is why modern C++ prefers smart pointers, which we'll explore next.

challenge icon

Challenge

Easy

Let's build a simple message storage system that demonstrates dynamic memory allocation with new and delete.

You'll create two files to organize your code:

  • MessageBox.h: Define a MessageBox class that dynamically manages an array of messages. The class should have:
    • A private pointer to a dynamically allocated array of strings
    • A private integer tracking the current count of messages
    • A private integer storing the maximum capacity
    • A constructor that takes a capacity and allocates the array using new[]
    • A destructor that properly frees the memory using delete[] and prints "MessageBox destroyed"
    • An addMessage(string msg) method that adds a message if there's room, returning true on success or false if full
    • A printAll() method that prints each stored message on its own line
  • main.cpp: Read a capacity value and a number of messages from input. Then read that many message strings. Create a MessageBox on the heap using new, add all the messages to it, call printAll(), and then properly delete the MessageBox to free memory.

The input format will be:

  • First line: the capacity (integer)
  • Second line: the number of messages to add (integer)
  • Following lines: one message per line

Remember: every new needs a matching delete, and every new[] needs a matching delete[]. After deleting, it's good practice to set pointers to nullptr.

Include your header file in main.cpp using #include "MessageBox.h".

Cheat sheet

Use new to allocate memory dynamically on the heap and get a pointer to it:

int* num = new int;        // Allocate single integer
*num = 42;                 // Assign value through pointer

Player* player = new Player("Hero");  // Allocate object

Every new must have a matching delete to free the memory:

delete num;      // Free single object
delete player;   // Calls destructor, then frees memory

For arrays, use new[] and delete[]:

int* scores = new int[5];    // Allocate array of 5 integers
scores[0] = 100;

delete[] scores;             // Free array - note the brackets!

Common mistakes to avoid:

// Memory leak - forgot to delete
int* ptr = new int(10);
ptr = new int(20);    // Lost access to first allocation!

// Dangling pointer - using after delete
delete ptr;
*ptr = 5;             // Undefined behavior!

// Mismatched delete
int* arr = new int[10];
delete arr;           // Wrong! Should be delete[]

After deleting, set pointers to nullptr to avoid accidental reuse.

Try it yourself

#include <iostream>
#include <string>
#include "MessageBox.h"
using namespace std;

int main() {
    int capacity;
    int numMessages;
    
    // Read capacity and number of messages
    cin >> capacity;
    cin >> numMessages;
    cin.ignore(); // Clear the newline after the number
    
    // TODO: Create a MessageBox on the heap using new
    
    // TODO: Read and add all messages to the MessageBox
    for (int i = 0; i < numMessages; i++) {
        string message;
        getline(cin, message);
        // Add message to the MessageBox
    }
    
    // TODO: Call printAll() to display all messages
    
    // TODO: Delete the MessageBox to free memory
    // Remember to set pointer to nullptr after deleting
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming