Unlike managed languages like Java or Python, C++ gives you direct control over memory allocation and deallocation. While this gives you high performance, it also requires you to carefully manage memory.
Sometimes you don't know how much memory you will need until runtime. You can dynamically allocate memory using the new keyword.
int* ptr = new int; // Dynamically allocate an integer *ptr = 100; cout << *ptr;
You can also allocate arrays dynamically:
int* arr = new int[5]; // Allocates memory for 5 integers
When you dynamically allocate memory using new, you must free it when you are done to prevent memory leaks. You do this with the delete keyword.
delete ptr; // Frees the memory allocated for the integer
For dynamically allocated arrays, use delete[]:
delete[] arr; // Frees the memory for the array
new needs a delete.nullptr after deletion:delete ptr; ptr = nullptr;
Mastering memory management is the key to becoming an expert C++ developer!
Which keyword is used to free dynamically allocated memory in C++?