0% found this document useful (0 votes)
3 views

L3_Dynamic Memory allocation in C++

The document provides an overview of dynamic memory allocation in C++ using pointers, highlighting the differences between static and dynamic memory allocation. It explains the use of the 'new' and 'delete' operators for memory management, including examples of allocating and deallocating memory for variables and arrays. Additionally, it discusses the implications of memory management, such as potential allocation failures and the importance of freeing memory to avoid leaks.

Uploaded by

parishree1906
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

L3_Dynamic Memory allocation in C++

The document provides an overview of dynamic memory allocation in C++ using pointers, highlighting the differences between static and dynamic memory allocation. It explains the use of the 'new' and 'delete' operators for memory management, including examples of allocating and deallocating memory for variables and arrays. Additionally, it discusses the implications of memory management, such as potential allocation failures and the importance of freeing memory to avoid leaks.

Uploaded by

parishree1906
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

SDF II(15B11CI211)

EVEN Semester 2025

2ND SEMESTER , FIRST YEAR


JAY P E E IN S T IT U T E OF IN F OR M AT I ON T E C H N OLOGY (J IIT ),
N OIDA
1
Lecture 3 – Dynamic Memory Allocation in C++ using Pointers

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.

• Runtime allocation or dynamic allocation of memory:


✔ The memory is allocated at runtime.
✔ The memory space is allocated dynamically within the program run.
✔ Dynamically allocated memory is allocated on the heap.
✔ The exact space or number of the data items does not have to be known by the compiler in advance.
✔ Pointers play a major role for dynamic memory allocation.

4
Static vs Dynamic memory allocations

Static Memory Allocation Dynamic Memory Allocation


Memory Allocates variables permanently Memory Allocates variables only if
program unit gets active
Memory Allocation is done before Memory Allocation is done during
program execution program execution
Use stack data structure for Use heap data structure for
implementation implementation
Less efficient More efficient
no Memory reusable memory reusable and can be freed when not
required

https://www.w3schools.in/difference-in-static-and-dynamic-memory-
allocation/

5
Dynamic Memory Allocation

For allocating dynamic memory, new operator is used.

• Memory de-allocation is also an important part of this concept


• The "clean-up" of storage space is done for variables or for other data storage.
• It is the job of the programmer to de-allocate dynamically created space.
• For de-allocating dynamic memory, delete operator is used.
• In other words, dynamic memory Allocation refers to performing memory management
for dynamic memory allocation manually.

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.

✔ new int; //dynamically allocates memory for an integer type


✔ new double; // dynamically allocates memory an double type
✔ new int[30]; // dynamically allocates memory for integer array

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

In the above example,


✔ we have declared a pointer variable ‘ptr’ to integer and initialized it to null.
✔ Using the “new” operator memory will be allocate to the “ptr” variable.

10
Example: new
int *ptr; //Pointer that can point to an integer
ptr = new int; //Now it points to allocated memory

if(!ptr) //NULL pointer returned


{
cout << "Allocation error\n";
}
else
{
*ptr = 100;
cout <<"Memory location: "<< ptr;
cout <<" contains the int value: "<< *ptr
<<endl;
delete ptr; //deallocate the memory
}
Example: new with initialization
int *ptr; //Pointer that can point to an integer
ptr = new int(87);
//Allocate memory and initialize to 87

if(!ptr) //NULL pointer returned


{
cout << "Allocation error\n";
}
else
{
cout <<"Memory location: "<< ptr;
cout <<" contains the int value: "<< *ptr
<<endl;
delete ptr; //deallocate the memory
}
Dynamic Memory Allocation for Arrays

• You can allocate one-dimensional arrays using new as


follows:
int *ptr;
ptr = new int[10];
• You may then use the pointer as you would a normal array.

• You may not specify an initialiser when allocating arrays.

• When an array allocated by using new is released, delete


must be told that it is an array. E.g:
delete [] ptr;
Dynamic Memory Allocation for Arrays
• To allocate memory for an array of characters, i.e., a string of 50 characters. Using that same syntax,
memory can be allocated dynamically
• char* str = NULL; // Pointer initialized with NULL
• str= new char[50]; // Dynamic Allocation will be done

• 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.

free() frees memory but doesn’t call Destructor of a class whereas


“delete” frees the memory and also calls the Destructor of the class.

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

memory allocated successfully


*i= 5
*a= 10
Array values:1 2 3 4 5
Dynamically Allocating Arrays:

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.

Then we declare an array of integer and allocate it space in memory dynamically


equal to the value stored in the len variable using this statement
int *marks = new int[length];

thus it is allocated a space equal to ‘length * (size of 1 integer)’.

The rest of the code is self-explanatory.

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

You might also like