L3_Dynamic Memory allocation in C++
L3_Dynamic Memory allocation in C++
2
Memory Allocation
✔ Memory allocation in programming is very important for storing values when you assign
them to variables
✔ allocates memory for the variables declared by a programmer via the compiler
✔ allocation is done either before or at the time of program execution
3
Ways for memory allocation
• Compile time allocation or static allocation of memory:
✔ The memory for named variables is allocated by the compiler.
✔ The memory allocated by the compiler is allocated on the stack.
✔ Exact size and storage must be known at compile time.
✔ for array declaration, the size has to be constant.
4
Static vs Dynamic memory allocations
https://www.w3schools.in/difference-in-static-and-dynamic-memory-
allocation/
5
Dynamic Memory Allocation
6
Memory Parts in C++ Program
• stack:
✔ All variables declared inside any function takes up memory from the stack.
• heap:
✔ It is the unused memory of the program and can be used to dynamically allocate the memory at
runtime.
7
Source: https://study.com/academy/lesson/how-to-allocate-deallocate-memory-in-c-
programming.html
8
The “new” Operator
• To allocate space dynamically, unary operator new is used , followed by the
type being allocated for memory.
It returns a NULL pointer if there is insufficient memory to fulfill the allocation request
9
Allocating space with new
• int * ptr=NULL; // declares a pointer ptr
• ptr = new int; // dynamically allocate an int for loading the address in ptr
• double * i; // declares a pointer i
• i = new double; // dynamically allocate a double and loading the address in i
10
Example: new
int *ptr; //Pointer that can point to an integer
ptr = new int; //Now it points to allocated memory
• Here, new operator allocates 50 continuous elements of type characters to the pointer variable str
and returns the pointer to the first element of str.
14
The Delete Operator
• The memory allocated dynamically using the new operator has to be freed explicitly by the programmer.
For this purpose, the “delete” operator is used
• The general syntax of the delete operator is:
delete pointer_variable;
• So memory allocated to the ptr variable can be freed as:
delete ptr;
• This statement frees the memory allocated to the variable “ptr” back to the memory pool.
• delete operator can also be used to free the memory allocated to arrays.
15
The Delete Operator
• the memory allocated to the array str above can be freed as follows:
delete[] str;
• Note the subscript operator used with the delete operator.
• This is because, as we have allocated the array of elements, we need to free all the
locations.
• Instead, if the following statement had executed:
delete str;
• the above statement will only delete the first element of the array.
• Using subscript “[]” all the memory allocated is to be freed.
16
Malloc()
• The malloc() function from C, also exists in C++,
• But it is recommended to avoid using malloc() function.
• malloc() allocates requested size of bytes and returns a pointer to the first byte of
allocated space.
• The main benefit of new over malloc() is that new doesn't just allocate memory, it
constructs objects which is a prime concept of C++.
•malloc(): It is a C library function that can also be used in C++, while
the “new” operator is specific for C++ only.
•Both malloc() and new are used to allocate the memory dynamically in
heap. But “new” does call the constructor of a class
whereas “malloc()” does not.
17
free() vs delete:
free() is a C library function that can also be used in C++, while “delete”
is a C++ keyword.
free() should only be used for deallocating the memory allocated either
using malloc(), calloc(), realloc() or for a NULL pointer.
18
Dynamic memory allocation Programming Example:1
#include <iostream>
using namespace std;
int main()
{
int* i= NULL;
i= new int;
*i= 5;
cout << "Value is : " << *i<< endl;
delete i;
}
19
Example 2 : new and delete operators in C++.
#include <iostream>
#include <string> double *arr= NULL;
using namespace std; arr= new double[10];
int main()
{ if(!arr)
int *p= NULL; {cout<<"memory not allocated"<<endl;}
p= new int(); else
int *a= new int(10); {
for(int i=0;i<5;i++)
if(!p) arr[i] = i+1;
{ cout<<“Array values : ";
cout<<"bad memory allocation"<<endl; for(int i=0;i<5;i++)
} cout<<arr[i]<<"\t";
else }
{ delete p;
cout<<"memory allocated successfully"<<endl; delete a;
*p= 5; delete[] arr;
cout<<"*p= "<<*p<<endl;
cout<<"*a= "<<*a<<endl; return 0;
}
20
21
Program Output
The major use of the concept of dynamic memory allocation is for allocating memory to an array when we have to
declare it by specifying its size but are not sure about it.
#include <iostream>
using namespace std;
for( int i = 0; i < len; i++ )
int main() {
cin >> *(marks+i);
{
int len, sum = 0; }
cout << "Enter the no. of students in the class" << endl;
for( int i = 0; i < len; i++ )
cin >> len; {
sum += *(marks+i);
int *marks = new int[len]; //Dynamic memory allocation
}
cout << "Enter the marks of each student" << endl;
cout << "sum is " << sum << endl;
}
return 0;
22
Explanation:
In this example first we ask the user for the number of students in a class and we
store its value in the len variable.
23
✔ There is a substantial difference between declaring a normal array and allocating dynamic memory for a block of
memory using new.
✔ The most important difference is that the size of a regular array needs to be a constant expression, and thus its size
has to be determined at the moment of designing the program, before it is run, whereas the dynamic memory
allocation performed by new allows to assign memory during runtime using any variable value as size.
✔ The dynamic memory requested by our program is allocated by the system from the memory heap.
✔ However, computer memory is a limited resource, and it can be exhausted.
✔ Therefore, there are no guarantees that all requests to allocate memory using operator new are going to be
granted by the system.
24
Questions
Create a dynamic array of pointers (to integers) of size 10 using new.
int **arr = new int* [10];
What Happens if the System's Memory Runs out During the Execution of the Program?
Allocation fails by throwing an exception of type std::bad alloc
To avoid exception use nothrow with new, it returns a NULL pointer
int* ptr = new(nothrow) int;
if (ptr == NULL){
cout << "Allocation Failed!\n";
}
25
#include<iostream>
using namespace std;
int main()
{
int *ptr = new int;
delete ptr;
delete ptr;
cout<<"hi";
return 0;
}
What will be output:-
Error
26
#include<iostream>
using namespace std;
int main()
{
int *ptr = NULL;
delete ptr;
cout<<" NO EFFECT";
return 0;
}
What will be output:-
NO EFFECT
27
References
• Robert Lafore, Object Oriented Programming in C++, SAMS, 2002
• https://www.softwaretestinghelp.com/new-delete-operators-in-cpp/
• https://www.softwaretestinghelp.com/stack-in-cpp/
• https://www.geeksforgeeks.org/
• https://www.tutorialspoint.com/abstract-data-type-in-data-structures
28