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

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 7 of 45 · C++

Lesson 15: Dynamic Memory Allocation (new, delete)

Duration: 10 min

Dynamic Memory Allocation (new, delete)\n\nC++ lets you allocate objects on the heap with new and release them with delete. This gives you control over lifetime beyond the current scope.\n\n---\n\n## Example: Allocating and Deallocating\ncpp\n// Single object\nint* p = new int(5); // value‑initialises to 5\nstd::cout << \"*p = \" << *p << '\\n';\ndelete p; // free memory\n\n// Dynamic array\nint* arr = new int[3]{1, 2, 3};\nfor (int i = 0; i < 3; ++i) {\n std::cout << arr[i] << ' ';\n}\nstd::cout << '\\n';\ndelete[] arr; // note the []\n\n\nFailure to delete leads to memory leaks. Modern C++ encourages RAII (Resource Acquisition Is Initialization) to automate cleanup.\n\n> Tip: Prefer smart pointers (std::unique_ptr<T[]>) for dynamic arrays to avoid manual delete[].\n\n---\n\n<Alert type="info">Never call delete on memory allocated with malloc, and never call free on memory allocated with new.

Previous: Lesson 14: ReferencesNext: Lesson 16: Smart Pointers – unique_ptr, shared_ptr, weak_ptr