C++ new and delete

🧠 C++ new and delete – Make and Break Memory Blocks

When you want to create variables while the program is running, you need dynamic memory. That’s where new and delete come in!

With new, you create a memory block. With delete, you clean it up. It’s like renting a room and returning the keys when done! 🏠

📌 Syntax of new and delete

int* ptr = new int;     // Allocate one int
*ptr = 50;              // Assign value

delete ptr;             // Free the memory

🧪 Example: Simple new and delete

#include <iostream>
using namespace std;

int main() {
    int* num = new int;  // Dynamically create an int
    *num = 42;           // Assign value

    cout << "Value: " << *num << endl;

    delete num;          // Clean up
    return 0;
}
  

Try It Now

🔢 Allocating Arrays

Need more than one block? You can use new[] and delete[] to handle arrays.

#include <iostream>
using namespace std;

int main() {
    int* numbers = new int[5]; // Allocate array of 5 ints

    for(int i = 0; i < 5; i++) {
        numbers[i] = i * 10;
    }

    for(int i = 0; i < 5; i++) {
        cout << numbers[i] << " ";
    }

    delete[] numbers; // Clean up array memory
    return 0;
}
  

Try It Now

⚠️ Why Use delete?

If you use new, always use delete. Not doing so causes a memory leak — memory stays allocated forever, even if you’re done using it! 🧯

✅ Summary

  • new creates dynamic memory at runtime.
  • delete frees that memory to avoid leaks.
  • Use new[] and delete[] for arrays.