WINSEM2023-24_BCSE102L_TH_VL2023240501147_2024-01-24_Reference-Material-II

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 36

Dynamic Memory Allocation in C

Dynamic Memory Allocation in C


• In programming, particularly in C, managing memory efficiently is
crucial. This begins with understanding the distinction between
Static and Dynamic Memory Allocation. Static Memory Allocation,
occurring at compile-time, assigns a fixed memory space to
variables or arrays. However, this predefined space can
sometimes be insufficient.
• Dynamic Memory Allocation, on the other hand, addresses this
limitation by allowing memory allocation and deallocation during
run-time.
• This is achieved through library functions
like malloc(), calloc(), realloc(), and free().
• Dynamic Memory Allocation is pivotal in C programming, as it is
integral to various data structures such as Linked Lists, Stacks,
Queues, and Trees, providing flexibility and efficiency in memory
management.
Difference between Static Memory Allocation and
Dynamic Memory Allocation
Static Memory Allocation Dynamic Memory Allocation
Constant (Invariable) memory is Dynamic (Variable) memory is
reserved at compile-time of our reserved at run-time of our program
program that can't be modified. that can be modified.
It is used at compile-time of our It is used at run-time of our program
program and is also known and is also known as run-time
as compile-time memory allocation. memory allocation.
We can't allocate or deallocate a We can allocate and deallocate a
memory block during run-time. memory block during run-time.
Stack space is used in Static Memory Heap space is used in Dynamic
Allocation. Memory Allocation.
It doesn't provide reusability of It provides reusability of memory,
memory, while the program is while the program is running. So, it
running. So, it is less efficient. is more efficient.
How Does Memory Management in C works?
• When we execute a C Program, it requires to reserve some memory in the
machine to store its variables, functions, instructions and the program file
itself. However, we also have a memory segment that we can use
dynamically as much memory as the system have and that too during the
run-time of a program. So, now let us see the components/segments of
memory that are used during the execution of a C program.
• There are further four components in which our system's memory is
divided:
• Stack Segment (Static Memory)
• Global Variables Segment (Static Memory)
• Instructions / Text Segment (Static Memory)
• Heap Segment (Dynamic Memory)
• Instructions / Text
Text outside the main() function is stored in the Static
Memory.
These instructions are stored during compile-time of a
program.
• Global Variables
Global variable also known as static variables and can be
declared by two methods,
Using static keyword, ex. static int i = 0;
Declaring variable outside main() or any other function.
These variables are stored in the Static Memory during the
compile-time of our program.
Stack
• Stack is a constant space (memory) allocated by our
operating system to store local variables, function
calls and local statements that are present in the
function definition. It is the major part of the Static
Memory in our system.
• There are some drawbacks of stack space as follows:
– The memory allocated for stack can't grow during the
run-time of an application.
– We can't allocate or deallocate memory during
execution.
Heap
• Heap is the Dynamic Memory of our program, It can be also
be imagined as a big free pool of memory available to us.
• The space occupied by heap section is not fixed, it can vary
during the run-time of our program and there are functions
to perform allocation and deallocation of memory blocks
during run-time.
• Heap space can grow as long as we do not run out of the
system's memory itself, however it is not in the best interest
of a programmer to exhaust the system's memory, so we
need to be really careful while using the heap space in our
program.
Memory Allocation Process
#include <stdio.h>
int sum; // global variable
// Declaring gcd and lcm functions, both takes two integer arguments,
// (memory will not be allocated upon declaring or defining our functions).
int greatestCommonDivisor(int, int);
int leastCommonMultiple(int, int);
// Defining greated common divisor function (also know as HCF).
int greatestCommonDivisor(int a, int b) {
while (a && b) {
if (a > b) {
a %= b;
} else {
b %= a;
}
}
return a + b;
}
// Defining least common multiple function by using greatest common divisor.
int leastCommonMultiple(int a, int b) {
return (a / greatestCommonDivisor(a, b)) * b;
}
int main() {
int x, y;
printf("Enter two values to find their Greatest Common Divisor and Least Common Multiple : ");
scanf("%d%d", &x, &y);
printf("Greatest Common Divisor : %d \nLeast Common Multiple : %d", greatestCommonDivisor(x, y),
leastCommonMultiple(x, y));
sum = greatestCommonDivisor(x, y) + leastCommonMultiple(x, y);
printf("\nSum of GCD and LCM : %d\n", sum);
return 0;
Explanation of Memory Allocation Process :
• The first rectangular box represents the memory reserved for text /
instructions, second box as memory reserved for global variables section,
third box as the space reserved for stack and fourth box represents the
heap space.
• When we run our program, first the main() function is called, then some
amount of memory from the stack frame is allocated for the execution of
main() function and as sum is a global variable, it has been given a space
in the global segment.
• Heap space remains empty throughout the execution of the program as
there is no allocation of memory during run-time.
• The amount of memory allocated for a function in the stack can be called
as a stack frame. All of the local variables, arguments and the information
in a function is stored within the stack frame allocated to that function
and as soon as a function returns something or reaches its last statement,
it is cleared from the stack memory.
• When the main() finishes, program also finishes. In the end, space
occupied by our global variables also gets cleared.
Introduction to Dynamic Memory Allocation in C

• Dynamic Memory Allocation in C is a process in


which we allocate or deallocate a block of memory
during the run-time of a program.
• Dynamic Memory Allocation is considered as a
very important concept in the field of Data
Structures and is used in almost every Data
Structures like Linked Lists, Stacks, Dynamic Arrays,
Queue, etc.
Dynamic memory allocation in c language is
possible by 4 functions of stdlib.h header file.

 malloc()
 calloc()
 realloc()
 free()
malloc() allocates single block of requested memory.

calloc() allocates multiple block of requested memory.

realloc() reallocates the memory occupied by malloc() or


calloc() functions.

free() frees the dynamically allocated memory.


malloc() function in C
• The malloc() function allocates single block of requested
memory.

• It doesn't initialize memory at execution time, so it has


garbage value initially.

• It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

ptr=(cast-type*)malloc(byte-size)
• The “malloc” or “memory allocation” method
in C is used to dynamically allocate a single
large block of memory with the specified size.
• It returns a pointer of type void which can be
cast into a pointer of any form.
• It doesn’t Initialize memory at execution time
so that it has initialized each bytes with the
default garbage value initially.
#include<stdio.h> for(i=0;i<n;++i)
{
#include<stdlib.h>
scanf("%d",ptr+i);
int main(){ sum+=*(ptr+i);
int n,i,*ptr,sum=0; }
printf("Enter number of elements: "); printf("Sum=%d",sum);
scanf("%d",&n); free(ptr);
ptr=(int*)malloc(n*sizeof(int)); return 0;
}
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
Example of malloc() in C
#include <stdio.h>
#include <stdlib.h> // Print the array elements
for (int i = 0; i < n; i++) {
int main() { printf("%d ", arr[i]);
int *arr; }
int n = 5;
// Free the allocated memory
free(arr);
// Allocate memory for an return 0;
//array of integers }
arr = (int *)malloc(n * sizeof(int));

// Initialize the array


for (int i = 0; i < n; i++) {
arr[i] = i+1;
}
calloc() function in C

• The calloc() function allocates multiple


block of requested memory.
• It initially initialize all bytes to zero.
• It returns NULL if memory is not
sufficient.
• The syntax of calloc() function is given
below:
• ptr=(cast-type*)calloc(number, byte-
size)
#include<stdio.h>
for(i=0;i<n;++i)
#include<stdlib.h>
{
int main(){ scanf("%d",ptr+i);
int n,i,*ptr,sum=0; sum+=*(ptr+i);
printf("Enter number of elements: "); }
scanf("%d",&n); printf("Sum=%d",sum)
ptr=(int*)calloc(n,sizeof(int)); free(ptr);
return 0;
if(ptr==NULL)
}
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
malloc() calloc()

Calloc accepts two arguments,(number of


Malloc accepts single argument, (size of a
elements for allocation, size of each
memory block for allocation)
element)
In malloc, return value is a pointer to the In calloc, return value is a pointer to the
first byte in the allocated block of first byte in the allocated block of
memory. memory.
Calloc allocates according to the specified
Malloc allocates only requested memory
number of blocks of memory of a specific
block of memory.
type.
In malloc, memory block is unitilialized In calloc, the memory block is initialized
and contains garbage values. with zero.
malloc() has high time efficiency calloc() has low time efficiency
Due to the initialization step, calloc() is
Malloc() is faster than calloc().
slower than malloc().
Syntax: void* calloc(size_t num, size_t
Syntax: void* malloc(size_t size);
size);
malloc() doesn't initialize memory to zero calloc() initiallized memory to zero.
Example of calloc() in C
#include <stdio.h>
#include <stdlib.h>
// Print the array elements
int main() { for (int i = 0; i < n; i++) {
int *arr; printf("%d ", arr[i]);
int n = 5; }

// Free the allocated memory


free(arr);
arr = (int *)calloc(n, sizeof(int)); return 0;
}
// Initialize the array
for (int i = 0; i < n; i++) {
arr[i] = i+1;
}
realloc() function in C
If memory is not sufficient for malloc() or
calloc(), you can reallocate the memory by
realloc() function.
In short, it changes the memory size.
• Let's see the syntax of realloc() function.
ptr=realloc(ptr, new-size)
#include <stdio.h>
#include <stdlib.h>

int main()
{

// This pointer will hold the


// base address of the block created
int* ptr;
int n, i;

// Get the number of elements for the array


n = 5;
printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using calloc()


ptr = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully


// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {

// Memory has been successfully allocated


printf("Memory successfully allocated using calloc.\n");

// Get the elements of the array


for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}

// Get the new size for the array


n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);

// Dynamically re-allocate memory using realloc()


ptr = (int*)realloc(ptr, n * sizeof(int));

// Memory has been successfully allocated


printf("Memory successfully re-allocated using realloc.\n");
// Get the new elements of the array
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}

return 0;
}
C free() method

• “free” method in C is used to dynamically de-


allocate the memory.
• The memory allocated using functions malloc() and
calloc() is not de-allocated on their own. Hence the
free() method is used, whenever the dynamic
memory allocation takes place.
• It helps to reduce wastage of memory by freeing it.
Syntax of free() in C
• free(ptr);
// Program to calculate the sum of n numbers entered by the user

#include <stdio.h>
#include <stdlib.h>

printf("Enter elements: ");


int main() {
for(i = 0; i < n; ++i) {
int n, i, *ptr, sum = 0;
scanf("%d", ptr + i);
sum += *(ptr + i);
printf("Enter number of elements: "); }
scanf("%d", &n);
printf("Sum = %d", sum);
ptr = (int*) malloc(n * sizeof(int));
// deallocating the memory
// if memory cannot be allocated free(ptr);
if(ptr == NULL) {
printf("Error! memory not allocated."); return 0;
exit(0); }
}
// Program to calculate the sum of n numbers entered by the user

#include <stdio.h>
#include <stdlib.h> printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
int main() { sum += *(ptr + i);
int n, i, *ptr, sum = 0; }
printf("Enter number of elements: ");
scanf("%d", &n); printf("Sum = %d", sum);
free(ptr);
return 0;
ptr = (int*) calloc(n, sizeof(int));
}
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int *ptr, *ptr1;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using malloc()


ptr = (int*)malloc(n * sizeof(int));

// Dynamically allocate memory using calloc()


ptr1 = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL) {
printf("Memory not allocated.\n");
exit(0);
}

else {

// Memory has been successfully allocated


printf("Memory successfully allocated using malloc.\n");

// Free the memory


free(ptr);
printf("Malloc Memory successfully freed.\n");
// Memory has been successfully allocated
printf("\nMemory successfully allocated using calloc.\n");

// Free the memory


free(ptr1);
printf("Calloc Memory successfully freed.\n");
}

return 0;
}

You might also like