codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚡

C++ Programming

37 / 87 topics
33Pointers34Pointers and Arrays35References36Call by Reference (Using Pointers)37Memory Management: new and delete
Tutorials/C++ Programming/Memory Management: new and delete
⚡C++ Programming

Memory Management: new and delete

Updated 2026-05-12
45 min read

Memory Management: new and delete

In this tutorial, we will explore how to manage dynamic memory in C++ using the new and delete operators. Understanding these concepts is crucial for efficient memory usage and avoiding common pitfalls such as memory leaks and dangling pointers.

Introduction

Memory management is a fundamental aspect of programming, especially in languages like C++. In C++, memory can be allocated either on the stack or the heap. The choice between these two depends on the specific requirements of your program. Understanding the differences between stack and heap allocation will help you make informed decisions about how to manage memory effectively.

Stack vs Heap

Stack Memory

  • Allocation: Automatically managed by the compiler.
  • Scope: Limited to the function in which it is declared.
  • Access Speed: Fast, as it follows a Last-In-First-Out (LIFO) principle.
  • Size Limitation: Typically smaller than heap memory.

Stack memory is used for storing local variables and function call information. The size of stack memory is limited and predefined by the operating system, making it suitable for small, fixed-size data.

Heap Memory

  • Allocation: Manually managed by the programmer using new and delete.
  • Scope: Global or can be passed around functions.
  • Access Speed: Slower than stack memory due to dynamic allocation.
  • Size Limitation: Larger than stack memory, but can lead to fragmentation.

Heap memory is used for storing dynamically allocated data. Unlike stack memory, heap memory requires manual management to prevent memory leaks and other issues.

The new Operator

The new operator is used to allocate memory on the heap. When you use new, it returns a pointer to the newly allocated memory.

Syntax

C++
1int* ptr = new int; // Allocates memory for an integer and returns its address

Example

Let's see how we can use new to allocate memory for an integer and initialize it.

example1.cpp
1#include <iostream>
2
3int main() {
4 int* ptr = new int; // Allocate memory for an integer
5 *ptr = 50; // Initialize the allocated memory with a value
6
7 std::cout << "Value: " << *ptr << std::endl; // Output the value
8
9 delete ptr; // Free the allocated memory
10 return 0;
11}
Output
Value: 50

In this example, we allocate memory for an integer using new, initialize it to 50, and then print its value. Finally, we free the allocated memory using delete.

The delete Operator

The delete operator is used to deallocate memory that was previously allocated with new. It is important to match each new with a corresponding delete to prevent memory leaks.

Syntax

C++
1delete ptr; // Frees the memory pointed to by ptr

Example

Continuing from the previous example, let's see how we can properly deallocate memory.

example2.cpp
1#include <iostream>
2
3int main() {
4 int* ptr = new int; // Allocate memory for an integer
5 *ptr = 50; // Initialize the allocated memory with a value
6
7 std::cout << "Value: " << *ptr << std::endl; // Output the value
8
9 delete ptr; // Free the allocated memory
10 return 0;
11}
Output
Value: 50

In this example, we ensure that the memory is properly deallocated using delete. Failing to do so would result in a memory leak.

Arrays and Memory Management

When dealing with arrays, you can use new[] and delete[] to allocate and deallocate memory.

Syntax

C++
1int* arr = new int[10]; // Allocates memory for an array of 10 integers
2delete[] arr; // Frees the allocated memory

Example

Let's see how we can use new[] and delete[] to manage an array of integers.

example3.cpp
1#include <iostream>
2
3int main() {
4 int* arr = new int[5]; // Allocate memory for an array of 5 integers
5
6 // Initialize the array
7 for (int i = 0; i < 5; ++i) {
8 arr[i] = i * 10;
9 }
10
11 // Print the array elements
12 for (int i = 0; i < 5; ++i) {
13 std::cout << "arr[" << i << "] = " << arr[i] << std::endl;
14 }
15
16 delete[] arr; // Free the allocated memory
17 return 0;
18}
Output
arr[0] = 0
arr[1] = 10
arr[2] = 20
arr[3] = 30
arr[4] = 40

In this example, we allocate memory for an array of 5 integers using new[], initialize it, and then print its elements. Finally, we free the allocated memory using delete[].

Common Pitfalls

Memory Leaks

A memory leak occurs when you allocate memory but fail to deallocate it. This can lead to a gradual loss of available memory over time.

Example

C++
1#include <iostream>
2
3int main() {
4 int* ptr = new int; // Allocate memory for an integer
5 *ptr = 50; // Initialize the allocated memory with a value
6
7 std::cout << "Value: " << *ptr << std::endl; // Output the value
8 // Forget to delete ptr here!
9 return 0;
10}

In this example, we allocate memory for an integer but forget to deallocate it using delete. This results in a memory leak.

Dangling Pointers

A dangling pointer is a pointer that points to a memory location that has been freed. Accessing or modifying the value of a dangling pointer leads to undefined behavior.

Example

C++
1#include <iostream>
2
3int main() {
4 int* ptr = new int; // Allocate memory for an integer
5 *ptr = 50; // Initialize the allocated memory with a value
6
7 std::cout << "Value: " << *ptr << std::endl; // Output the value
8
9 delete ptr; // Free the allocated memory
10 std::cout << "Value after deletion: " << *ptr << std::endl; // Undefined behavior
11 return 0;
12}

In this example, we access the value of ptr after it has been deleted, leading to undefined behavior.

Practical Example

Let's create a complete program that demonstrates dynamic memory management using new and delete.

practical_example.cpp
1#include <iostream>
2
3class Rectangle {
4public:
5 int width;
6 int height;
7
8 Rectangle(int w, int h) : width(w), height(h) {}
9
10 int area() const {
11 return width * height;
12 }
13};
14
15int main() {
16 // Allocate memory for a Rectangle object
17 Rectangle* rect = new Rectangle(10, 20);
18
19 // Access and print the area of the rectangle
20 std::cout << "Area: " << rect->area() << std::endl;
21
22 // Free the allocated memory
23 delete rect;
24 return 0;
25}
Output
Area: 200

In this example, we define a Rectangle class and dynamically allocate memory for an instance of it using new. We then access its area and print it. Finally, we free the allocated memory using delete.

Summary

ConceptDescription
Stack MemoryAutomatically managed by the compiler; limited size; fast access.
Heap MemoryManually managed by the programmer; larger size but can lead to fragmentation.
new OperatorAllocates memory on the heap and returns a pointer to it.
delete OperatorDeallocates memory that was previously allocated with new.
ArraysUse new[] and delete[] for managing arrays of objects.
Memory LeaksOccur when allocated memory is not deallocated; can lead to loss of available memory.
Dangling PointersPoint to freed memory; accessing them leads to undefined behavior.

What's Next?

In the next tutorial, we will explore Object-Oriented Programming (OOP) concepts in C++. OOP provides a structured way to organize code and manage complexity, making it easier to write maintainable and scalable software.

Stay tuned!


PreviousCall by Reference (Using Pointers)Next OOP Concepts Overview

Recommended Gear

Call by Reference (Using Pointers)OOP Concepts Overview