0 ratings 0% found this document useful (0 votes) 55 views 8 pages Dynamic Memory Allocation in C
The document explains dynamic memory allocation in C programming, highlighting its advantages over static memory allocation. It details the use of pointers and standard library functions such as malloc, calloc, realloc, and free for managing memory at runtime. Additionally, it contrasts static and dynamic memory allocation, emphasizing the flexibility and efficiency of dynamic allocation for handling varying data sizes during program execution.
AI-enhanced title and description
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save dynamic memory allocation in c For Later 43 Dynamic Memory)
PT ; Allocation
jearning Outcomes
rafter reading #
chapter, the readers will be able to
a@ Explain dynamic memory allocation using pointers.
| To choose appropriate means of making the best use of available memory in dynamic
applications.
we Formulate allocation and deallocation techniques with suitable data types.
When a C program is compiled, the compiler allocates memory to store different data
elements such as constants, variables (including pointer variables), arrays, and structures.
‘This is referred to as compile-time or static memory allocation. There are several limitations
in such static memory allocation: like allocation is done in memory exclusively allocated
toa program, which is often limited in size. The C language provides a very simple
solution to overcome these limitations: dynamic memory allocation in which the memory
is allocated at run-time, ie. during the execution of a program. Dynamic memory
management involves the use of pointers and four standard library functions, namely,
malloc, calloc, realloc, and free. The first three functions allocate memory, whereas the
last function returns memory to the system (also called freeing/deallocating memory).
‘The pointers are used to point to the blocks of memory allocated dynamically.
r When we think of creating something, we think of creating from the very scratch, but
— is not what happens when a computer creates a variable ‘X’ (say); to the computer, it
more like an allocation; the computer assigns a memory cell from a lot of pre-existing
537_ Problem Solving using Proprammin,
in ¢
memory cells (0 X, 11 is Tike someone named ‘RAJESH’ heing allocated tea hota
‘a lot of free or empty pre-existing rooms, 1 rem, From,
Now, what is Static Memory Allocation? When we d
the variables that will be used so that the compiler kno
important part of the program that the user wants, not
So. when we declare variables, the compiler allocates those variables to there
to the hotel analogy in the previous paragraph). N SOMA (ref,
low, if we see this is being dene
the program executes, we cannot allocate variables by this method while the p,,,
executing. bes
jcclare variables, we prs
knows that the varinhle cP*"* al
\t just a rogue symbol Nontin ;
nid,
hefom
fram i,
1” All the variables in the below program are statically allocated.
void fund)
{
int a;
}
int mainQ.
{
int b;
int ¢[10]
}
Q Why must we introduce another allocation method if this gets the job done?
Why would we need to allocate memory while the program is executing? Because even
though it is not blatantly visible, not being able to allocate memory during run time preelud.,
flexibility and compromises space efficiency. Especially in those eases where the input is net
known beforehand, we suffer in terms of inefficient storage use and lack or excess of slots
to enter data (given an array or similar data structures to store entries). So, here we define
Dynamic Memory Allocation (DMA), the mechanism by which storage/memory/cells
can be allocated to variables during the run time. As we have been going through it
all, it allocates the memory during the run time, enabling us to use as much storage as we
want without worrying about any waste. DMA does not operate during compile time. The
allocation and deallocation of memory dynamically occur during runtime using functions
like malloc) and freeQ in C language. So, DMA is a runtime concept and doesn’t directly
relate to compile time operations.
int main)
{
11 Below variables are allocated memory
/ dynamically.
int *ptrl = new int;
int *ptr2 = new int{10];
// Dynamically allocated memory is deallocated
delete ptr1;
delete ptr2;nic Memory Allocation ao
. ess of allocating memory at run-time in known nn dynamic memory allocation.
The Patines, Known as memory management functions, ure used for Allocating and
memory during the execution of a program. These functions are defined
th heador file, Dynamic memory allocation in C language is possible hy four functions
« Fre learning the above functions, let us understand the diferene between sate and
aynami¢ ‘memory allocation.
iy
able 13.1: Difference between static and dynamic memory allocation
Static Memory Allocation Dynamic Memory Allocation
Memory is allocated at compile time.
Memory is allocated at run time.
Memory cannot be increased while Memory can be increased while executing a
executing the program. program.
Used in an array. Used in a linked list.
Table 13.2: Functions with their description
Function Description
malloc() “Allocates the requested size of bytes and returns a void pointer pointing
to the first byte of the allocated space
calloc() ‘Allocates space for an array of elements, initialize them to zero, and
then returns a void pointer to the memory |
free()
realloc()
Releases previously allocated memory
Modify the size of previously allocated space 1
Usinr Alloction Process
Global vari aa,
ee variables, static variables, and program instructions get their memory in @
le ee storage area, whereas local variables are stored in a memory area called Stack.
Wed for ee between these two regions is known as the Heap area. This region is
8 kee mie Memory allocation during the execution of the program. The size of the
“PS changing,a
&
Problem Solving using Programming
ing
if(ptr==NULL)
{
printf(‘Sorry! unable to allocate memory”);
exit(0);
}
printf(“Enter elements of array: ");
scanf(“%d",ptr+i);
sum+=*(ptr+i);
}
printf(‘Sum=%d",sum);
free(ptr);
return 0;
}
Output:
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
Difference between malloc() and calloc()
Table 13.3: Difference between malloc and calloc function
calloc() malloc)
1. calloc() initializes the allocated memory | 1. malloc( initializes the allocated memory
with a 0 value. with garbage values.
2. The number of arguments is 2 2. The number of arguments is 1
3. Syntax: (cast_type *) 3, Syntax: (cast_type *)malloc(Size in bt
calloc(blocks,size_of_block);
13.2.3 realloc() in C:
i realloc() changes the memory size already allocated dynamically to & variable.
Syntax:
void* realloc(pointer, new-size)
Example: realloc()
int *x;= Memory Allocation
amie Memory 543
2 ¢ne*)malloc(60 * sizeoftint));
* 7 (int*)realloc(s,100); “allocated a new memory to variable x
memory is not sufficient for malloc Q or callocQ, you can reallocate the memory by
) function. In short, it changes the memory size.
s see the syntax of realloc() function.
ealloc(ptr, new-size);
sing realloc()
It
eal
tu
ptr
syntax:
‘sample:
aude
e
includ
jnt main
‘ int *ptr, i, nl, n2;
printf(‘Enter size of array: ”);
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf(‘Address of previously allocated memory: ");
ford = 0; i< nl; +4)
printf(‘%ou\t”,ptr + i);
printf(‘\nEnter new size of array: ");
seanf(‘%d”, &n2);
ptr = realloc(ptr, n2);
for(i = 0; i < 2; +4)
printf(‘%u\t”, ptr + i);
return 0;
}
Output
Enter size of array: 5
Address of previously allocated memory: 2153310912 2153310916 —- 2158310920
2153310924 2153310928
Enter new size of array: 4
2153810912 «2153310916 «2153310920 2153310924
13.24 freeQ) in C:
The memory occupied by malloc() or calloc() functions must be released by calling the
ad function. Otherwise, it will consume memory until the program exit. Let us see the
‘tax of free) function.
free(ptr),
Example: Using C malloc() and free()
_Problem Solving using pP,
TORtamm
544
; d the sum of
write a program apes nare atone a .
em jin :
programs allocate ™ ment ene
#include :
#include
int main
{ i rs
int num, i, “ptr, sum = 0;
print{Enter number of elements: »;
seanf(‘%d", &num);
per = Gat) malloc(num * sizeof(nd)); memory allocated using malic
if(ptr == NULL)
{
printf(“Error! memory not allocated.”);
exit(0);
}
printf(‘Enter elements of array: ”);
for(i = 0; i < num; ++i)
{
scanf(“%d", ptr + i);
sum += *(ptr + i);
}
printf(‘Sum = %d”, sum);
free(ptr);
return 0;
}
Output
Enter number of elements: 5
Enter elements of array: 10
20
30
40
50
Sum = 150
Example: Using C calloc() and free()
mee aC program to find the sum of n elements entered by a user. To perform
Program, allocate memory dynamically using calloc) function.
#include
#include
int main),
-. Memory Allocation
amie Bab
{
jne num, i, *PET sum = 0;
printfEnter number of elements: ");
wcanf%0, &num);
“or = dnt*) calloc(num, sizeoftint));
pe
NULL)
ip =
printf(‘Error! memory not allocated.”);
exit(0);
}
}
printf(‘Enter elements of array: ”);
for(i = 0; i < num; ++i)
scanf("%d”, ptr + i);
sum += *(ptr + i);
}
printf(‘Sum = %d”, sum);
free(ptr);
return 0;
}
Output
Enter number of elements: 5
Enter elements of array: 10 20 30 40 50
Sum = 150
tis a variable used to store another variable’s address.
this address store the address
of variable rate, 1004 here
Sa
int s_rate;
ie 1000 1001
Se aay eae
s_rate rate
Second variable
Figure 13.2: Dynamic Memory Allocation using pointer546 Problem Solving using Programming in
c
Advantage of pointer:
© Returns multiple values from a function
e Accesses any memory location
@ Improves the performance
@ Reduces the code
@ Used for dynamic memory allocation
@ Used in arrays, functions, and structures
Table 13.4: Symbols with description
Description
address of operator Determines the address of a variable.
indirection operator Accesses the value at the address.
Example:
#include
#include
void main()
{
clrser(); 7
int n=50;
int *p; //declaration of pointer
p=&n; //stores the address of number of variables
printf(“Address of n variable is %x \n”,&n);
printf(“Address of p variable is %x \n”,p);
printf(“Value of p variable is %d \n”,*p);
getchQ;
}
Output:
Address of n variable is fff4
Address of p variable is fff4
Value of p variable is 50
‘iaiieieiietetiiicmmnbataneniattitiemesieeet ane