Dynamic_memory
Dynamic Memory Allocation
Section titled “Dynamic Memory Allocation”Dynamic memory allocation allows you to allocate memory at runtime. This chapter covers new, delete, and memory management techniques.
Memory Allocation with new
Section titled “Memory Allocation with new”// Allocate single objectint* ptr = new int(42);
// Allocate arrayint* arr = new int[10];
// Allocate and initializedouble* d = new double(3.14);
// Zero-initializeint* zero = new int(); // 0Deallocation with delete
Section titled “Deallocation with delete”int* ptr = new int(42);delete ptr; // Free single object
int* arr = new int[10];delete[] arr; // Free arrayCommon Mistakes
Section titled “Common Mistakes”// Memory leakint* ptr = new int[100];// Forgot to delete!
// Double deletedelete ptr;delete ptr; // Undefined behavior!
// Wrong deleteint* arr = new int[10];delete arr; // Should be delete[]
// Dangling pointerint* ptr = new int(42);delete ptr;std::cout << *ptr; // Use after free!Placement new
Section titled “Placement new”Construct object at specific memory location:
#include <new>
char buffer[sizeof(int)];int* ptr = new (buffer) int(42);ptr->~int(); // Must manually destructComplete Example: Manual Memory Management
Section titled “Complete Example: Manual Memory Management”#include <iostream>
class Buffer {private: int* data; size_t size;
public: Buffer(size_t s) : size(s) { data = new int[size](); // Zero-initialized std::cout << "Allocated " << size << " ints\n"; }
~Buffer() { delete[] data; std::cout << "Freed buffer\n"; }
int& operator[](size_t i) { return data[i]; } size_t getSize() const { return size; }};
int main() { Buffer buf(100); buf[0] = 42; std::cout << "Value: " << buf[0] << "\n";
return 0; // Destructor called automatically}Key Takeaways
Section titled “Key Takeaways”- Always match
newwithdelete,new[]withdelete[] - Set pointer to nullptr after delete
- Prefer smart pointers in modern C++
- Prefer std::vector over manual dynamic arrays