Lesson 7 of 45 · C++
Lesson 15: Dynamic Memory Allocation (new, delete)
Duration: 10 min
Lesson 7 of 45 · C++
Duration: 10 min
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.