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

Lec 12 - Dynamic Memory Allocation

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

Lec 12 - Dynamic Memory Allocation

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

CSE-275

Course Title: Computer Programming Language

Lec – 12 Dynamic Memory


Allocation

Lec Tasnim Ullah Shakib

1
Before we start…

What is compile time? And what is run time?

• Compile time is the period of time when the C code is compiled to the machine code.
It is the duration when the C file (for eg, code.c) is converted to an executable file (for eg,
code.exe).

• Runtime is the period of time when the program in the executable file is running.
Runtime occurs after compile time.
It is the duration when you see the black console window on your screen.

2
Static Memory Allocation

int main(){
int a[4];
}

• Memory for this array is allocated in compile time while declaring.


• This array has a fixed size.
• Its size cannot be changed during runtime.
• For the above code, 4 memories will be allocated before runtime.

Integer array a of size 4


3
Static Memory Allocation
int main(){
int a[4] = {3,7,5};
}

• If there are only 3 elements in the array, then 1of the memory will be wasted.

• Again, what if after running the program, more than 4 memory are needed?

• So, there is no chance to allocate memory as per need.


Either there will be memory wastage, or memory shortage.
4
Dynamic Memory Allocation (Probable Solution…)
int main(){
int n;
scanf(“%d”,&n);
int arr[n];
}

• For this code, you take user input after running the program.
• So, now the array size will be allocated in runtime.
• But once the array size is allocated, can you further change the size of the array? No.
• So, this becomes a fixed size array as well.
• Its size cannot be changed later in the runtime.

HOW TO CHANGE THE SIZE OF THE ARRAY WHENEVER WE NEED DURING


RUNTIME?
5
Dynamic Memory Allocation
● Dynamic Memory Allocation can be defined as a procedure in which the size of an array can be
changed/assigned during the runtime.

● C provides some functions to achieve these tasks.

● There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic
memory allocation in C programming.

● They are:
■ malloc()
■ calloc()
■ realloc()
■ free()

6
Dynamic Memory Allocation - malloc()
● The name "malloc" stands for memory allocation.
● It is used to dynamically allocate a single large block of memory with the specified size and type.
● It returns a pointer of type void which can be typecasted into a pointer of any form.
● Syntax:
ptr = (cast-type*) malloc(byte-size)
● For example:
ptr = (int*) malloc(12);
This will create a memory block of 12 byte.
The pointer ptr holds the address of the first byte in the allocated memory.
Since the size of int is 4 bytes, we can store 3 elements in this block.

ptr
12 byte memory block

7
Dynamic Memory Allocation - malloc()

● It is a good practice to write the syntax as:


ptr = (cast-type*) malloc(no._of_elements * sizeof(cast_type))

● For example:
ptr = (int*) malloc(3* sizeof(int));

● It initializes each block with default garbage value.

● If space is insufficient, allocation fails and returns a NULL pointer. So it is always better to
check whether the block has been created or failed.

8
Dynamic Memory Allocation - malloc()
12 bytes of single block of memory

3 elements, each 4 bytes


So, 3*4 = 12 bytes of single block of memory

Use sizeof(), in case you forget the


number of bytes of the datatype

Here, a user wants to dynamically


create an integer array of n elements

9
Dynamic Memory Allocation - malloc()
Checking whether
memory was
allocated or not by
seeing whether a is
null pointer or not.
Terminate the
program if memory
not allocated.

Now, the pointer a can be


used just like an array.

10
Dynamic Memory Allocation - malloc()
Question: Using dynamic memory allocation, find the sum of all elements of an input n size float array.

11
Dynamic Memory Allocation - malloc()

int main(){
int n;
scanf(“%d”,&n);
int* arr;
arr=(int*)malloc(n*sizeof(int));
}

12
Dynamic Memory Allocation - calloc()

int main(){
int n;
scanf(“%d”,&n);
int* arr;
arr=(int*)calloc(n,sizeof(int));
}

13
Dynamic Memory Allocation - calloc()
● The name “calloc" stands for contiguous allocation.
● It is used to dynamically allocate the specified number of blocks of memory of the specified
size and type.
● It returns a pointer of type void which can be cast into a pointer of any form.
● Syntax:
ptr = (cast-type*) calloc(n, byte-size)
● For example:
ptr = (int*) calloc(3, sizeof(int));
This will create 3 memory blocks of 4 byte.
The pointer ptr holds the address of the first block’s first byte.
Since the size of int is 4 bytes, we can store 3 elements in this block.

ptr
3 memory blocks, each of 4 byte

14
Dynamic Memory Allocation - calloc()
● It initializes each block with default 0 value.

● If space is insufficient, allocation fails and returns a NULL pointer. So it is always better to check
whether the block has been created or failed.

3 blocks of memory with each storing an integer of 4 bytes.


So, 3*4 = 12 bytes

Use sizeof(), in case you forget the


number of bytes of the datatype

Here, a user wants to dynamically


create a character array of n elements

15
Malloc() vs Calloc()

● Malloc assigns single block of requested memory,


Calloc assigns multiple blocks of the requested memory.

● Malloc takes only one argument,


Calloc takes two arguments.

● Malloc initializes each block with default garbage value,


Calloc initializes each block with 0.

● Malloc is faster as it does not need to initialize values with default garbage,
Calloc is slower as it needs to initialize values with 0.

16
Dynamic Memory Allocation - realloc()
● The name “realloc" stands for re-allocation.

● It is used to dynamically change the memory allocation of a previously allocated memory.

● In other words, realloc can be used to dynamically increase or decrease the memory size that has
been previously allocated with malloc or calloc.

● It returns a pointer of type void which can be cast into a pointer of any form.

● Syntax:
ptr = (cast-type*) realloc(pointer-name, new-byte-size);

● If space is insufficient, allocation fails and returns a NULL pointer.

17
Dynamic Memory Allocation - realloc()

int main()
{
int n = 3; calloc allocates
int* a = array of size 3
(int*)calloc(n,sizeof(int)); a[0]
= 4; a[1] = 6; a[2] = 7;
realloc increases
int n1 = 4; array size to 4
a = (int*)realloc(a,n1*sizeof(int));
realloc decreases
int n2 = 2; array size to 2
a = (int*)realloc(a,n2*sizeof(int));
}

Using realloc(), one can reallocate memories in run time again.

18
Dynamic Memory Allocation - realloc()
● Re-allocation of memory maintains the already present value and new blocks will be initialized
with default garbage value.

ptr

2 5 12 garbage garbage garbage garbage garbage garbage garbage


1000 1004 1008 1012 1016 1020 1024 1028 1032 1036

Integer array of size 3

ptr

2 5 12 garbage garbage garbage garbage garbage garbage garbage


1000 1004 1008 1012 1016 1020 1024 1028 1032 1036

Integer array extended to size 5


19
Dynamic Memory Allocation - realloc()
● If there is not enough space for re-allocation in the current location, the compiler will copy the
values into new memory locations and initialize new blocks there with default garbage value.

ptr

2 5 12 garbage 95 garbage garbage garbage garbage garbage


1000 1004 1008 1012 1016 1020 1024 1028 1032 1036

Integer array of size 3 Integer x

ptr

2 5 12 garbage 95 2 5 12 garbage garbage


1000 1004 1008 1012 1016 1020 1024 1028 1032 1036

Integer x Integer array copied and extended to size 5

20
Dynamic Memory Allocation - free()
● “free” method in C is used to dynamically de-allocate the memory.

● The memory allocated using functions malloc(), calloc(), and realloc() is not de-allocated on their
own.

● These memories must be freed explicitly.

● Hence the free() method should be used at the end of the program, after the dynamic memory
allocation takes place.

● It helps to reduce wastage of memory by freeing it and giving it back to the system.

● Syntax:
free(pointer_name);
21
Dynamic Memory Allocation - free()

int main(){
int n;
scanf(“%d”,&n);
int* arr = (int*)calloc(n,sizeof(int));
arr[0] = 4;
arr[1] = 6;
int n1;
scanf(“%d”,&n1);
arr = (int*)realloc(arr,n1*sizeof(int));
free(arr);
}

22
Dynamic Memory Allocation - Problem

Question: You are asked to maintain a record for the Level-1 CGPA of a class of 60 MIST students
on a low memory computer. The CGPAs of all the students needs to be manually entered by you by
looking through their certificates. Now at the end of Level-1, more N students will join the class
from BAFA and BNA if the average CGPA of the MIST students is more than 3. And so the CGPA of
the new students needs to get added into the record as well. It is also likely that your computer
may not even have the capacity to allocate all these records.

Write a C program to store the CGPA records for the above scenario using the most suitable
memory allocation technique.

23
Dynamic Memory Allocation - Solution

24
Thank You

Special thanks to Lec Afia


Miss & Lec Tasneem Miss for
some of the slide contents

25

You might also like