Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 15: Dynamic Memory Allocation (ne | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

Lesson 15 of 45

·C++

Lesson 15: Dynamic Memory Allocation (new, delete)

10 min

Course progress33%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Using new for single objects and arrays
  • Corresponding delete and delete[]
  • Avoiding memory leaks and dangling pointers
  • RAII concept introduction

Dynamic Memory Allocation (new, delete)

C++ lets you allocate objects on the heap with new and release them with delete. This gives you control over lifetime beyond the current scope.


Example: Allocating and Deallocating

// Single object
int* p = new int(5);   // value‑initialises to 5
std::cout << \"*p = \" << *p << '\
';
delete p;               // free memory

// Dynamic array
int* arr = new int[3]{1, 2, 3};
for (int i = 0; i < 3; ++i) {
    std::cout << arr[i] << ' ';
}
std::cout << '\
';
delete[] arr;            // note the []

Failure to delete leads to memory leaks. Modern C++ encourages RAII (Resource Acquisition Is Initialization) to automate cleanup.

Tip: Prefer smart pointers (std::unique_ptr<T[]>) for dynamic arrays to avoid manual delete[].


<Alert type="info">Never call delete on memory allocated with malloc, and never call free on memory allocated with new.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 14: ReferencesContinue to lesson 16Lesson 16: Smart Pointers – unique_ptr, shared_ptr, weak_ptrBack to C++ Course curriculum