You are on page 1of 62

Dynamic Memory Allocation in C++

Slide 1
This region holds the compiled code of the
program. Here, all the functions of the
program start at a specific address.
In this region, global variables are
stored during the entire lifetime of the
program.

Slide 2
What is a stack?

• A stack is a Last In First Out data structure


• In order to access other elements remove those that
are on top one by one.

Slide 3
Stack

Slide 4
Stack

Slide 5
Stack

Slide 6
Stack

Slide 7
Stack

Slide 8
Stack

Slide 9
Stack

Slide 10
Stack

Slide 11
Function Call Stack in Action

• Function call stack after the operating system invokes main to


execute the application

• First the operating system calls main this pushes an activation


record onto the stack
• The activation record tells main how to return to the operating
system (i.e., transfer to return address R1) and contains the space
for main's automatic variable (i.e., a, which is initialized to 10).

Slide 12
Function call stack after the operating system
invokes main to execute the application.

Slide 13
• Function main before returning to the operating calls function square.

This causes a stack frame for square to be pushed onto the function call
stack .

This stack frame contains the return address that square needs to return
to main (i.e., R2) and the memory for square's automatic variable (i.e., x).
• After square calculates the square of its argument, it needs to return to main and
no longer needs the memory for its automatic variable x.

So the stack is popped giving square the return location in main (i.e., R2) and
losing square's automatic variable.

Figure shows the function call stack after square's activation record has been
popped.

lFunction main now displays the result of calling square , then executes the return statement. This
causes the activation record for main to be popped from the stack. This gives main the address it
needs to return to the operating system (i.e., R1)and causes the memory for main's automatic
variable (i.e., a) to become unavailable.
Square function used to demonstrate the function

Slide 16
Slide 17
Memory Allocation

new
delete
{ int* ptr;
int a[200]; ptr = new int[200];
… …
} delete [] ptr;
Slide 18
Memory Management

Static Memory Allocation


– Memory is allocated at compilation time

Dynamic Memory
– Memory is allocated at running time

Slide 19
Slide 21
Heap

• A heap is a region of computer’s memory, used for dynamic


memory allocation.
• When you use dynamic allocation, all the created variables
are stored into a heap.
• Heap memory is not managed automatically.
• When you use dynamic memory allocation, a pointer that is
located in stack points to the region of the allocated memory
in heap.

Slide 22
Heap

Slide 23
Static vs Dynamic Objects

• Static object • Dynamic object


(variables as declared in function – Memory is acquired by
calls) program with an allocation
– Memory is acquired request
automatically new operation

– Dynamic objects can exist


– Memory is returned beyond the function in which
automatically when object they were allocated
goes out of scope
– Object memory is returned
by a deallocation request
delete operation

Slide 24
Object (variable) creation: New

Syntax
ptr = new SomeType;

where ptr is a pointer of type SomeType

Example
int* p = new int;
Uninitialized int variable

Slide 25
Object (variable) destruction: Delete

Syntax
delete p;
storage pointed by p is returned to free store and p is now undefined

Example
int* p = new int;
*p = 10;
delete p;

p 10
Slide 26
New Operator in C++

• The new operator denotes a request for memory allocation on the


Heap. If sufficient memory is available, new operator initializes the
memory and returns the address of the newly allocated and initialized
memory to the pointer variable.
• Syntax to use new operator: To allocate memory of any data type,
the syntax is:

pointer-variable = new data-type;

Here, pointer-variable is the pointer of type data-type. Data-type


could be any built-in data type including array or any user defined
data types including structure and class.

Slide 27
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;

OR

// Combine declaration of pointer


// and their assignment
int *p = new int;

Slide 28
Initialize memory: We can also initialize the memory using new
operator:
pointer-variable = new data-type(value);
Example:
int *p = new int(25);
float *q = new float(75.25);

Allocate block of memory: new operator is also used to allocate a


block(an array) of memory of type data-type.

pointer-variable = new data-type[size];

where size(a variable) specifies the number of elements in an array.


• Allocate a block of memory
• The new operator is also used to allocate a block(an array) of memory
of type data-type.
• Syntax: pointer-variable = new data-type[size];
• Example:
int *p = new int[10]
• Dynamically allocates memory for 10 integers continuously of
type int and returns pointer to the first element of the sequence,
which is assigned to p(a pointer). p[0] refers to first element, p[1]
refers to second element and so on.
Normal Array Declaration vs Using new

• Normal arrays are deallocated by compiler (If array is


local, then deallocated when function returns or
completes).
• However, dynamically allocated arrays always remain
there until either they are deallocated by programmer or
program terminates.

Slide 31
What if enough memory is not available during runtime?

• If enough memory is not available in the heap to allocate, the new


request indicates failure by throwing an exception of type
std::bad_alloc, unless “nothrow” is used with the new operator, in
which case it returns a NULL pointer.
• Therefore, it may be good idea to check for the pointer variable
produced by new before using it program.

int *p = new(nothrow) int;


if (!p)
{
cout << "Memory allocation failed\n";
}

Slide 32
delete operator

• Since it is programmer’s responsibility to deallocate


dynamically allocated memory, programmers are provided
delete operator by C++ language.
• Syntax:

// Release memory pointed by pointer-variable


delete pointer-variable;

 Here, pointer-variable is the pointer that points to the data object


created by new.

delete p;
delete q;
Slide 33
• To free the dynamically allocated array pointed by pointer-
variable, use following form of delete:

// Release block of memory


// pointed by pointer-variable
delete[] pointer-variable;

Example:
// It will free the entire array
// pointed by p.
delete[] p;

Slide 34
delete Operator in C++

• Once you do not need memory allocated by operator new, you


have to release it. You can do it by using operator delete:

• Syntax:

• delete pointer; for single object and

• delete[ ] pointer; for an array of objects

Slide 35
Array of New: dynamic arrays

• Syntax
P = new SomeType[Expression];
– Where
• P is a pointer of type SomeType
• Expression is the number of objects to be
constructed -- we are making an array

• Because of the flexible pointer syntax, P can be considered


to be an array

Slide 36
Example
Dynamic Memory Allocation
 Request for “unnamed” memory from the Operating System

new

 int *p, n=10; p


p = new int;

new
p = new int[100];
p
new
p = new int[n]; p
Slide 37
Freeing (or deleting) Memory

Slide 38
Slide 40
Slide 41
new and delete operators in C++
C++ Program to store CGPA of n number of students and display it
where n is the number of students entered by user

Slide 44
Slide 45
Slide 46
C++ Program to store CGPA of n number of students and display it where n is the
number of students entered by user

Slide 47
• The output of this program is same as the above program.

• When the object s is created, the constructor is called which


allocates the memory for num floating-point data.

• When the object is destroyed, i.e, when the object goes out
of scope, destructor is automatically called.

~Test() {
delete[] ptr;
}
• This destructor executes delete[] ptr; and returns memory
back to the operating system.
Slide 50
Which operator returns address of unallocated blocks in memory?
1.The delete operator
2.The empty operator
3.The new operator
4.All of them
Which operator returns address of unallocated
blocks in memory?

1.The delete operator


2.The empty operator
3.The new operator
4.All of them

The new operator


Which of the following is not a false statement about new
operator?

a. It can’t be overloaded.
b. It returns garbage value when memory allocation fails.
c. It automatically computes the size of the data object.
d. All of these
Which of the following is not a false statement about new
operator?

a. It can’t be overloaded.
b. It returns garbage value when memory allocation fails.
c. It automatically computes the size of the data object.
d. All of these
Which of the following operator is used to release the
dynamically allocated memory in C++?

a. remove
b. free
c. delete
d. both b and c

Slide 55
Which of the following operator is used to release the
dynamically allocated memory in C++?

a. remove
b. free
c. delete
d. both b and c

Slide 56
Which of the following is/are valid ways to allocate
memory for an integer by dynamic memory allocation in
C++?

a. int *p = new int(100);


b. int *p; p = new int; *p = 100;
c. int *p = NULL; p = new int; *p=100;
d. Only 1,2
e. All of these

Slide 57
Which of the following is/are valid ways to allocate
memory for an integer by dynamic memory allocation in
C++?

a. int *p = new int(100);


b. int *p; p = new int; *p = 100;
c. int *p = NULL; p = new int; *p=100;
d. Only 1,2
e. All of these

Slide 58
During dynamic memory allocation in CPP, new
operator returns _________ value if memory
allocation is unsuccessful.

a. False
b. NULL
c. Zero
d. None of these

Slide 59
During dynamic memory allocation in CPP, new operator
returns _________ value if memory allocation is
unsuccessful.

a. False
b. NULL
c. Zero
d. None of these

Slide 60
What will be the output ?

Slide 61
Output :

$main
Constructor called!
Constructor called!
Constructor called!
Constructor called!
Destructor called!
Destructor called!
Destructor called!
Destructor called!

You might also like