SlideShare a Scribd company logo
2
Most read
5
Most read
6
Most read
Dynamic Memory Allocation
Dynamic memory allocation is used to obtain and release
memoryduring program execution. Up until this point we
reserved memory at compile time using declarations.
wehaveto becarefulwith dynamic memoryallocation. It
operates at alow-level, you will often find yourself having to do a
certain amount of work to manage the memory it gives you.
For DMA, we must include the stdlib.h header file.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
1
⚫ Dynamic memory management refers to manual memory
management. This allows you to obtain more memory when required
and releaseit when not necessary
.
⚫ Although C inherently does not have any technique to allocate
memory dynamically, there are 4 library functions defined under
<stdlib.h> for dynamic memory allocation.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
2
Function
⚫ malloc()
⚫ calloc()
⚫ free()
⚫ realloc()
Use of Function
Allocatesrequested size of bytes and
returns apointer first byte of allocated
space
Allocatesspace for an arrayelements,
initializes to zero and then returns a pointer to
memory
deallocate the previouslyallocated space
Change the size of previouslyallocated space
Dymanic Memoryallocation
3
malloc()
The name malloc stands for "memory allocation".
The function malloc() reserves a block of memory of
specified size and return a pointer of type void which can be
casted into pointer of any form.
Syntax of malloc()
ptr = (cast-type*) malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function
returns a pointer to an area of memory with size of byte size.
If the space is insufficient, allocation fails and returns NULL
pointer.
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate either 200 or 400 according to
size of int 2 or 4 bytes respectively and the pointer points to
the address of first byte of memory.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
malloc() example
To allocate space for 100 integers:
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
int *ip;
if ((ip = (int*)malloc(100 *
sizeof(int))) == NULL){
printf("out of memoryn");
exit();
}
⚫ Note we cast the return value to int*.
⚫ Note we also check if the function returns NULL.
Allocating memory for a struct
W
e can alsoallocate memory for astruct.
Example:
struct node *newPtr;
newPtr = (struct node *)malloc(sizeof(struct
node));
Memory allocated with malloc() lastsaslong aswe want it to.
It does not automaticallydisappearwhen afunction returns, asautomatic-
duration variablesdo, but it does not haveto remain for the entire
duration ofyour program, either.There isamechanismto free allocated
memory.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
free()
Torelease allocated memory use
free()
⚫ Deallocatesmemory allocated bymalloc().
⚫ T
akesapointer asan argument.
e.g.
free(newPtr);
Freeingunused memory is agood idea,but it's not mandatory.When
your program exits,anymemory which it hasallocatedbut not
freed will be automaticallyreleased.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
free()
⚫Dynamically allocated memory created with either calloc() or
malloc() doesn't get freed on its own. we must explicitly use
free() to release the space.
syntax of free()
free(ptr);
⚫This statement frees the space allocated in the memory pointed
byptr.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
calloc()
⚫ The name calloc stands for "contiguous allocation".
⚫ The only difference between malloc() and calloc() is that, malloc() allocates single
block of memory whereas calloc() allocates multiple blocks of memory each of same
size and sets all bytes to zero.
Syntax of calloc()
⚫ ptr = (cast-type*)calloc(n, element-size);
⚫Thisstatement will allocate contiguous space in memory for an array of n elements.
Forexample:
ptr = (float*) calloc(25, sizeof(float));
Thisstatement allocates contiguous space in memory for an array of 25 elements each
of size of float, i.e, 4 bytes.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
calloc() example
/* Using calloc() to initialize 100 floats to 0.0 */
#include <stdlib.h>
#include <stdio.h>
#define BUFFER_SIZE 100
int main(){
float * buffer;
int i;
if ((buffer = (float*)calloc(BUFFER_SIZE, sizeof(float))) == NULL){
printf("out of memoryn");
exit(1);
}
for (i=0; i < BUFFER_SIZE; i++)
printf(“buffer[%d] = %fn”, i, buffer[i]);
return 0;
}
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
realloc()
⚫If the previously allocated memory is insufficient or more than
required, we can change the previously allocated memory size
usingrealloc().
Syntax of realloc()
ptr = realloc(ptr, newsize);
Here, ptr is reallocated with size of newsize.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
realloc()
Ifyou find you did not allocate enoughspace use realloc().
Y
ougive realloc() apointer (such asyou received from aninitial call
to malloc()) andanewsize,andrealloc doeswhatit canto give
you ablock of memory bigenoughto hold the new size.
int *ip;
ip = (int*)malloc(100 * sizeof(int));
...
/* need twice as much space */
ip = (int*)realloc(ip, 200 *
sizeof(int));
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array:");
scanf("%d", &n1);
ptr = (int*) malloc(n1 *
sizeof(int));
printf("Addressof previously
allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%ut",ptr + i);
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
printf(" nEnter new size of array:
");
scanf("%d", &n2);
ptr = realloc(ptr, n2);
for(i = 0; i < n2; ++i)
printf("%u t", ptr + i);
return 0;
}
printf("Error! memory not
allocated.");
exit(0);
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
#include <stdio.h> }
#include <stdlib.h> printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
int main() {
{ scanf("%d", ptr + i);
int num, i, *ptr, sum = 0; sum += *(ptr + i);
printf("Enter number of elements: "); }
scanf("%d", &num); printf("Sum = %d", sum);
ptr = (int*) malloc(num *sizeof(int)); free(ptr);
if(ptr == NULL) return 0;
{ }
Memory Allocation - calloc()
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
Dymanic Memoryallocation
15
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, num;
float *data;
printf("Enter total number of
elements(1 to 100): ");
scanf("%d", &num);
data = (float*) calloc(num,
sizeof(float));
if(data == NULL)
{
printf("Error!!! memory not
allocated.");
Exit(0);
}
printf("n");
for(i = 0; i < num; ++i)
{
printf("Enter Number %d:", i +
1);
scanf("%f", data + i);
}
for(i = 1; i < num; ++i)
{
if(*data < *(data + i))
*data = *(data + i);
}
printf("Largest element = %.2f",
*data);
return 0;
}
Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation

More Related Content

PPTX
Dynamic Memory allocation
PPTX
DYNAMIC MEMORY ALLOCATION.pptx
PPTX
DYNAMIC MEMORY ALLOCATION.pptx
PPTX
final GROUP 4.pptx
PPTX
dynamic_v1-3.pptx
PPT
Dynamic memory allocation
PPTX
Dynamic Memory Allocation(DMA)
PPT
CLanguage_ClassPPT_3110003_unit 9Material.ppt
Dynamic Memory allocation
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
final GROUP 4.pptx
dynamic_v1-3.pptx
Dynamic memory allocation
Dynamic Memory Allocation(DMA)
CLanguage_ClassPPT_3110003_unit 9Material.ppt

Similar to Dynamic Memory Allocation in C programming (20)

PPTX
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
PPTX
Dynamic Memory Allocation in C
PPTX
Dynamic memory allocation
PPTX
Memory management CP
PPTX
Dynamic memory allocation
PPTX
Dynamic memory Allocation in c language
PPTX
Dynamic Memory Allocation in C Programming | IIES Guide
PPTX
PPTX
Dynamic memory allocation
PPTX
Dynamic memeory allocation DMA (dyunamic momory .pptx
PDF
Dynamic memory allocation
PPTX
Dynamic memory allocation in c
PPTX
dynamicmemoryallocation.pptx
PPTX
Lecture 3.3.1 Dynamic Memory Allocation and Functions.pptx
PDF
Data Structure - Dynamic Memory Allocation
DOCX
Dma
PPTX
Dynamic memory allocation
PPTX
Dynamic memory allocation
PPSX
4 dynamic memory allocation
PPT
Bullet pts Dyn Mem Alloc.pptghftfhtfytftyft
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
Dynamic Memory Allocation in C
Dynamic memory allocation
Memory management CP
Dynamic memory allocation
Dynamic memory Allocation in c language
Dynamic Memory Allocation in C Programming | IIES Guide
Dynamic memory allocation
Dynamic memeory allocation DMA (dyunamic momory .pptx
Dynamic memory allocation
Dynamic memory allocation in c
dynamicmemoryallocation.pptx
Lecture 3.3.1 Dynamic Memory Allocation and Functions.pptx
Data Structure - Dynamic Memory Allocation
Dma
Dynamic memory allocation
Dynamic memory allocation
4 dynamic memory allocation
Bullet pts Dyn Mem Alloc.pptghftfhtfytftyft
Ad

More from Rhishav Poudyal (6)

PPTX
Array and its operation in C programming
PPTX
Chapter 1 (C-programming)Block diagram of computer
PPTX
Datatype and Operators used in C Programming
PPTX
Control Structure in C-programming with examples
PPTX
User defined function in C.pptx
PPTX
Shannon Capacity.pptx
Array and its operation in C programming
Chapter 1 (C-programming)Block diagram of computer
Datatype and Operators used in C Programming
Control Structure in C-programming with examples
User defined function in C.pptx
Shannon Capacity.pptx
Ad

Recently uploaded (20)

PPTX
Lesson notes of climatology university.
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Institutional Correction lecture only . . .
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Insiders guide to clinical Medicine.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Basic Mud Logging Guide for educational purpose
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Cell Types and Its function , kingdom of life
Lesson notes of climatology university.
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Institutional Correction lecture only . . .
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Insiders guide to clinical Medicine.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Microbial diseases, their pathogenesis and prophylaxis
Module 4: Burden of Disease Tutorial Slides S2 2025
Renaissance Architecture: A Journey from Faith to Humanism
FourierSeries-QuestionsWithAnswers(Part-A).pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
O7-L3 Supply Chain Operations - ICLT Program
Basic Mud Logging Guide for educational purpose
01-Introduction-to-Information-Management.pdf
Cell Types and Its function , kingdom of life

Dynamic Memory Allocation in C programming

  • 1. Dynamic Memory Allocation Dynamic memory allocation is used to obtain and release memoryduring program execution. Up until this point we reserved memory at compile time using declarations. wehaveto becarefulwith dynamic memoryallocation. It operates at alow-level, you will often find yourself having to do a certain amount of work to manage the memory it gives you. For DMA, we must include the stdlib.h header file. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation 1
  • 2. ⚫ Dynamic memory management refers to manual memory management. This allows you to obtain more memory when required and releaseit when not necessary . ⚫ Although C inherently does not have any technique to allocate memory dynamically, there are 4 library functions defined under <stdlib.h> for dynamic memory allocation. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation 2 Function ⚫ malloc() ⚫ calloc() ⚫ free() ⚫ realloc() Use of Function Allocatesrequested size of bytes and returns apointer first byte of allocated space Allocatesspace for an arrayelements, initializes to zero and then returns a pointer to memory deallocate the previouslyallocated space Change the size of previouslyallocated space
  • 3. Dymanic Memoryallocation 3 malloc() The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form. Syntax of malloc() ptr = (cast-type*) malloc(byte-size) Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer. ptr = (int*) malloc(100 * sizeof(int)); This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 4. malloc() example To allocate space for 100 integers: Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation int *ip; if ((ip = (int*)malloc(100 * sizeof(int))) == NULL){ printf("out of memoryn"); exit(); } ⚫ Note we cast the return value to int*. ⚫ Note we also check if the function returns NULL.
  • 5. Allocating memory for a struct W e can alsoallocate memory for astruct. Example: struct node *newPtr; newPtr = (struct node *)malloc(sizeof(struct node)); Memory allocated with malloc() lastsaslong aswe want it to. It does not automaticallydisappearwhen afunction returns, asautomatic- duration variablesdo, but it does not haveto remain for the entire duration ofyour program, either.There isamechanismto free allocated memory. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 6. free() Torelease allocated memory use free() ⚫ Deallocatesmemory allocated bymalloc(). ⚫ T akesapointer asan argument. e.g. free(newPtr); Freeingunused memory is agood idea,but it's not mandatory.When your program exits,anymemory which it hasallocatedbut not freed will be automaticallyreleased. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 7. free() ⚫Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own. we must explicitly use free() to release the space. syntax of free() free(ptr); ⚫This statement frees the space allocated in the memory pointed byptr. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 8. calloc() ⚫ The name calloc stands for "contiguous allocation". ⚫ The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero. Syntax of calloc() ⚫ ptr = (cast-type*)calloc(n, element-size); ⚫Thisstatement will allocate contiguous space in memory for an array of n elements. Forexample: ptr = (float*) calloc(25, sizeof(float)); Thisstatement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 9. calloc() example /* Using calloc() to initialize 100 floats to 0.0 */ #include <stdlib.h> #include <stdio.h> #define BUFFER_SIZE 100 int main(){ float * buffer; int i; if ((buffer = (float*)calloc(BUFFER_SIZE, sizeof(float))) == NULL){ printf("out of memoryn"); exit(1); } for (i=0; i < BUFFER_SIZE; i++) printf(“buffer[%d] = %fn”, i, buffer[i]); return 0; } Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 10. realloc() ⚫If the previously allocated memory is insufficient or more than required, we can change the previously allocated memory size usingrealloc(). Syntax of realloc() ptr = realloc(ptr, newsize); Here, ptr is reallocated with size of newsize. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 11. realloc() Ifyou find you did not allocate enoughspace use realloc(). Y ougive realloc() apointer (such asyou received from aninitial call to malloc()) andanewsize,andrealloc doeswhatit canto give you ablock of memory bigenoughto hold the new size. int *ip; ip = (int*)malloc(100 * sizeof(int)); ... /* need twice as much space */ ip = (int*)realloc(ip, 200 * sizeof(int)); Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 12. #include <stdio.h> #include <stdlib.h> int main() { int *ptr, i , n1, n2; printf("Enter size of array:"); scanf("%d", &n1); ptr = (int*) malloc(n1 * sizeof(int)); printf("Addressof previously allocated memory: "); for(i = 0; i < n1; ++i) printf("%ut",ptr + i); Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation printf(" nEnter new size of array: "); scanf("%d", &n2); ptr = realloc(ptr, n2); for(i = 0; i < n2; ++i) printf("%u t", ptr + i); return 0; }
  • 13. printf("Error! memory not allocated."); exit(0); Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation #include <stdio.h> } #include <stdlib.h> printf("Enter elements of array: "); for(i = 0; i < num; ++i) int main() { { scanf("%d", ptr + i); int num, i, *ptr, sum = 0; sum += *(ptr + i); printf("Enter number of elements: "); } scanf("%d", &num); printf("Sum = %d", sum); ptr = (int*) malloc(num *sizeof(int)); free(ptr); if(ptr == NULL) return 0; { }
  • 14. Memory Allocation - calloc() Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 15. Dymanic Memoryallocation 15 #include <stdio.h> #include <stdlib.h> int main() { int i, num; float *data; printf("Enter total number of elements(1 to 100): "); scanf("%d", &num); data = (float*) calloc(num, sizeof(float)); if(data == NULL) { printf("Error!!! memory not allocated."); Exit(0); } printf("n"); for(i = 0; i < num; ++i) { printf("Enter Number %d:", i + 1); scanf("%f", data + i); } for(i = 1; i < num; ++i) { if(*data < *(data + i)) *data = *(data + i); } printf("Largest element = %.2f", *data); return 0; } Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation