Software and Systems Engineering Standards: Verification and Validation of Sy...
Dynamic Memory Allocation
1. Active Learning Assignment
Semester : 3rd
Branch : CE Engineering
Subject : Data Structures(2130702)
Topic : “Dynamic Memory Allocation”
Prepared by : Vaani Pathak
Enrollement No. :170120107131
Guided by : Prof. Ketan Pandya
1Gandhinagar Institute of Technology
2. Introduction to Dynamic Memory
Allocation
• Dynamic Allocation is by which a program can
obtain memory while it is running.
• Pointers provide necessary support for C’s
powerful dynamic memory allocation.
• In general global variables are allocated
storage at compile time. Local variables can
use the program stack.
4. Malloc()
• It dynamically allocates memory during the
program.
• Prototype of this function is
Void*malloc(size_t, number_of_bytes).
After a successful call, malloc() returns a pointer
to the first byte of the region of memory.
5. Example of Malloc()
• Example:-
Code fragments below allocate 1000 bytes of
contiguous memory.
char*p;
p=(char*)malloc(1000);
Here,(char*)forces void pointer to become a
character
6. Program For Malloc()
#include<stdio.h>
#include<conio.h>
Void main()
{
int n, I, *p, sum=0;
printf(“enter elements: ”)
Scanf(“%f”, &n);
printf(“using malloc n:”);
p=(int*)malloc(n*size of (int));
if(p==NULL)
{
printf(“Error”);
}
printf(“enter elements of arrays:”);
For(i=0,i<n,i++)
8. Free() Function
• It is the opposite of malloc().
• It returns previously allocated memory to the
system.
• Prototype: void free(void*p);
• It is critical that you never call free() with an
invalid argument. That will delete the free list.
9. Calloc() function
• Calloc() function allocates an amount of
memory equal to num*size.
• It allocates enough memory for an array of
num objects and size bytes long.
• Memory allocated by calloc() is released by
free() function.
• Prototype:
• void*calloc(size_t,n,size_t,number_of_bytes);
10. Example of Calloc()
• Example of Calloc()
• Code fragments below dynamically allocates 100
elements to an integer array.
Int*p;
p=(int*)calloc(100,sizeof(int));
(int*) forces the void pointer to become a integer
11. Program for Calloc()#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
Void main()
{
int, I,n, *ptr, sum=0;
clrscr();
printf(“enter any number:”);
scanf(“%d”, &n);
ptr=(int*)calloc(n size of (int));
if)ptr==null);
{
printf(“!Error”);
exit(o);
}
printf(“enter elements of array:”);
for(i=o;i<n;++i)
{
scanf(“%d”, ptr +1);
sum+=*(ptr+1);
}printf(“sum=%d”,sum);
free(ptr);
Getch();
}
12. Difference between Malloc() and
Calloc()
Malloc()
• In Malloc, how much memory we want we can
pass it as one slot.
• Malloc is faster than calloc.
• Malloc dosnt initializes the allocated
memory.It contains garbage values.
13. …
Calloc()
• We need to split ad pass the memory as we
want.
• Calloc is slower than malloc.
• Calloc initialize the allocated memory to zero.
• Number of arguments is 2.