Dynamic memory allocation in c++ using new and delete
Dynamic memory allocation in C++ is the process of allocating memory at runtime, rather than at compile time. This is done using the new
and delete
operators.
new
Operator
The new
operator is used to dynamically allocate memory for an object or an array. It returns a pointer to the allocated memory.
Syntax: void* new type()
Example:
int* p = new int; // allocate memory for an integer
In this example, p
is a pointer to an integer, and new int
allocates memory for an integer.
delete
Operator
The delete
operator is used to deallocate memory that was previously allocated using new
. It takes a pointer to the memory to be deallocated as an argument.
Syntax: void delete type*
Example:
delete p; // deallocate memory for the integer
In this example, delete p
deallocates the memory that was allocated for the integer using new int
.
Example Program
Here is a simple example program that demonstrates dynamic memory allocation using new
and delete
:
#include <iostream>
int main() {
int* p = new int; // allocate memory for an integer
*p = 10; // assign a value to the integer
std::cout << "*p = " << *p << std::endl; // print the value of the integer
delete p; // deallocate memory for the integer
return 0;
}
Best Practices
Here are some best practices to keep in mind when using new
and delete
:
- Use smart pointers: Instead of using raw pointers and
new
/delete
, consider using smart pointers likeunique_ptr
orshared_ptr
to manage memory. - Use containers: Instead of allocating memory manually, consider using containers like
std::vector
orstd::list
to manage memory. - Avoid raw pointers: Try to avoid using raw pointers and
new
/delete
as much as possible, as they can lead to memory leaks and other issues. - Use
delete[]
for arrays: When deallocating memory for an array, usedelete[]
instead ofdelete
. - Check for null: Always check if a pointer is null before deleting it, to avoid crashes or undefined behavior.
Common Pitfalls
Here are some common pitfalls to avoid when using new
and delete
:
- Memory leaks: Failing to deallocate memory can lead to memory leaks, which can cause your program to consume more and more memory over time.
- Double deletion: Deleting the same memory twice can cause undefined behavior or crashes.
- Null pointer deletion: Deleting a null pointer can cause undefined behavior or crashes.
- Incorrect deallocation: Failing to deallocate memory correctly can lead to memory leaks or other issues.
By following best practices and avoiding common pitfalls, you can use new
and delete
effectively and safely in your C++ programs.