🏭
Memory Management

new & delete

C++ Ka Dynamic Memory
💡 new/delete C ke malloc()/free() ka C++ version hai — same kaam (heap se memory lo/wapas do), lekin new khud object ka constructor bhi chalata hai, delete destructor bhi chalata hai (malloc/free sirf raw memory dete hain).

new expression heap par memory allocate karta hai AUR agar type ek class hai, uska constructor bhi call karta hai — malloc() sirf raw bytes deta hai, koi initialization nahi. delete memory free karta hai AUR destructor bhi call karta hai.

Array allocate karne ke liye new[] aur delete[] use hota hai (alag syntax) — single object ke new/delete se mix mat karo, warna undefined behavior hai.

class Point {
  public:
    int x, y;
    Point(int x, int y) : x(x), y(y) {
      cout << "Constructor called" << endl;
    }
    ~Point() {
      cout << "Destructor called" << endl;
    }
};

int main() {
  Point *p = new Point(3, 4);   // constructor auto-chalta hai
  cout << p->x << endl;
  delete p;                      // destructor auto-chalta hai

  int *arr = new int[5];    // array allocation
  delete[] arr;               // array deallocation — [] zaroori
  return 0;
}
🏭
new/delete C ke malloc()/free() ka C++ version hai — same kaam (heap se memory lo/wapas do), lekin new khud object ka constructor bhi chalata hai, delete destructor bhi chalata hai (malloc/free sirf raw memory dete hain).
1 / 6
⚡ Quick Recap
  • new = malloc() + constructor call
  • delete = free() + destructor call
  • Array ke liye new[]/delete[] — mismatch undefined behavior hai
On this page (2 subtopics)

"Placement new" ek existing memory location par object construct karta hai (naya memory allocate kiye bina) — advanced technique, usually custom memory allocators ya performance-critical code mein use hoti hai. Beginners ko usually iski zaroorat nahi padti.

#include <new>

char buffer[sizeof(Point)];
Point *p = new (buffer) Point(1, 2);  // buffer mein hi construct hua, naya alloc nahi

p->~Point();  // manually destructor call karna padta hai — delete use nahi hota
💡Tip: Placement new sirf tab use karo jab genuinely custom memory management chahiye (game engines, embedded systems) — normal application code mein almost kabhi zaroorat nahi padti.

C++11 se nullptr introduce hua — type-safe null pointer constant. NULL (C se inherited) actually 0 ka macro hai, jo kabhi-kabhi ambiguity create kar sakta hai (integer 0 se confuse ho sakta hai overloaded functions mein). nullptr modern C++ mein hamesha prefer kiya jaata hai.

int *p1 = NULL;      // purana style, kaam karta hai
int *p2 = nullptr;    // modern, type-safe — preferred

void func(int x) { cout << "int version" << endl; }
void func(int *p) { cout << "pointer version" << endl; }

func(NULL);      // ambiguous ho sakta hai (kuch compilers mein)!
func(nullptr);    // hamesha pointer version — clear
💡Tip: Modern C++ code likhte waqt hamesha nullptr use karo, NULL ya 0 nahi — koi ambiguity nahi rehti aur intent clear hota hai.