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 objectEvery new must have a matching delete to free the memory:
delete num; // Free single object
delete player; // Calls destructor, then frees memoryFor 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
EasyLet'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 aMessageBoxclass 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, returningtrueon success orfalseif 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 aMessageBoxon the heap usingnew, add all the messages to it, callprintAll(), 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 objectEvery new must have a matching delete to free the memory:
delete num; // Free single object
delete player; // Calls destructor, then frees memoryFor 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;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container