4 Dynamic Memory
4 Dynamic Memory
Allocation
1
Dynamic Memory
2
3
4
Memory Allocation
5
Object (variable) creation:
New Operator
The "new" operator in C++
The new operator in C++ is used to dynamically allocate a
block of memory and store its address in a pointer variable
during the execution of a C++ program if enough memory is
available in the system.
7
Object (variable) destruction:
9
Problem with Arrays
Sometimes
Amount of data cannot be predicted beforehand
Number of data items keeps changing during program execution
Example: Seach for an element in an array of N elements
One solution: find the maximum possible value of N and allocate
an array of N elements
Wasteful of memory space, as N may be much smaller in some
executions
Example: maximum value of N may be 10,000, but a particular
run may need to search only among 100 elements
Using array of size 10,000 always wastes memory in most
cases
10
Better Solution
Dynamic memory allocation
Know how much memory is needed after the program
is run
Example: ask the user to enter from keyboard
Dynamically allocate only the amount of memory
needed
C++ provides functions to dynamically allocate
memory
11
Array Declaration Using the "new" Operator
The new operator can also be used to
allocate a block of memory (an array) of
any data_type.
Syntax:
data_type* ptr_var = new
data_type[size_of_the_array];
Example:
int* arr = new int[5];
12
Dynamically deallocating an array
13
Dynamic Memory Allocation in C++ for Objects
We can dynamically allocate memory for objects also. When
we create an object of a class,
a constructor function is invoked. Constructor is a member
function of a class that is used to initialize the object.
Also, when the object goes out of scope or gets de-
allocated, a destructor function is invoked. Destructor is also
a class member function that helps in knowing when the
object's memory gets deleted.
14
Dynamic Memory Allocation in C++ for Objects
class Animal
{
public:
Animal() {
cout << "Animal class constructor invoked!" <<endl; }
~Animal() {
cout << "Animal class destructor invoked!" <<endl; }
};
int main() {
// memory allocated for dog object of type Animal
// constructor will be invoked
Animal* dog = new Animal;
// memory deallocated for dog object of type Animal
// destructor will be invoked
delete dog;
return 0; } 15