In this tutorial, we will learn how to dynamically allocate and deallocate memory in C++. We will explore the new
and delete
operators and understand how to use them effectively to manage memory.
By the end of this tutorial, you will be able to:
- Understand dynamic memory allocation and deallocation in C++
- Use new
and delete
operators efficiently
- Identify and apply best practices for dynamic memory management
A basic understanding of C++ syntax and programming concepts such as variables, data types, and pointers is required.
Dynamic memory allocation is the process of assigning memory during runtime. In C++, we use the new
operator to allocate memory dynamically.
Syntax:
pointerVariable = new dataType;
This will allocate memory of size dataType
and the address is assigned to the pointerVariable
.
To deallocate or free the memory assigned dynamically, we use the delete
operator.
Syntax:
delete pointerVariable;
This will free up the memory that was previously allocated to pointerVariable
.
int* ptr = new int;
if(ptr == nullptr) {
// Memory allocation failed
cout << "Memory allocation failed\n";
return 0;
}
*ptr = 5;
cout << "Value: " << *ptr << "\n";
delete ptr; // deallocating memory
Here, we allocate memory for an integer using new
. We check if the memory is successfully allocated. If yes, we assign a value to it and print it. Finally, we deallocate the memory using delete
.
Expected output:
Value: 5
In this tutorial, we learned about dynamic memory allocation and deallocation in C++. We learned how to use the new
and delete
operators to manage memory effectively. We also discussed some best practices for memory management.
Now that you know how to manage memory, try to implement it in your projects. You can also learn about memory leaks and how to detect and prevent them.
Write a program to dynamically allocate memory for a float variable, assign a value and print it.
float* ptr = new float;
if(ptr == nullptr) {
cout << "Memory allocation failed\n";
return 0;
}
*ptr = 3.14;
cout << "Value: " << *ptr << "\n";
delete ptr;
This allocates memory for a float, assigns a value of 3.14, and prints it. Finally, it deallocates the memory.
Write a program to dynamically allocate memory for an array of integers, assign values, and print them.
int* ptr = new int[5];
if(ptr == nullptr) {
cout << "Memory allocation failed\n";
return 0;
}
for(int i=0; i<5; i++) {
ptr[i] = i+1;
}
for(int i=0; i<5; i++) {
cout << ptr[i] << " ";
}
delete[] ptr;
This allocates memory for an array of 5 integers, assigns values, and prints them. Finally, it deallocates the memory.
Remember, when deallocating memory allocated for arrays, use delete[]
instead of delete
.