C++ new and delete
πβ C++ new and delete
In C++, new and delete are used for dynamic memory managementβthat is, allocating and freeing memory at runtime (on the heap).
πΉ 1. Why new and delete?
Size of data not known at compile time
Memory needed dynamically (runtime)
Manual control over memory (powerful but risky)
πΉ 2. Using new (Allocate Memory)
Allocate a Single Variable
Or with initialization:
β Memory allocated on heap
β p stores the address
πΉ 3. Using delete (Free Memory)
β Frees heap memory
β Setting to nullptr avoids dangling pointer
πΉ 4. Complete Example (Single Variable)
πΉ 5. Dynamic Array Allocation (new[])
Initialize dynamically:
πΉ 6. Delete Dynamic Array (delete[])
β οΈ Important rule
newβdeletenew[]βdelete[]
πΉ 7. Complete Example (Dynamic Array)
πΉ 8. new vs Stack Allocation
| Stack | Heap |
|---|---|
| Automatic | Manual |
| Fast | Slower |
| Limited | Large |
| Safe | Error-prone |
πΉ 9. Common Mistakes β
β Memory Leak
β Double Delete
β Wrong Delete
β Correct:
πΉ 10. new/delete vs Smart Pointers (Modern C++)
β Old style:
β Modern C++:
β Automatic memory management
β No leaks
β Best Practices
Always pair
newwithdeleteAlways pair
new[]withdelete[]Set pointer to
nullptrafterdeletePrefer smart pointers (
unique_ptr,shared_ptr)Avoid raw
new/deletein modern C++
π Summary
newallocates memory on heapdeletefrees allocated memorynew[]/delete[]for arraysIncorrect usage leads to memory bugs
Prefer smart pointers when possible
