Memorey allocation
Functions
1.Static Memorey
Allocation
2.Dynamic Memorey
Allocation
1.Static Memorey
Allocation: If memorey space to be allocated for various variables is
decided during compilation time itself, then memorey space can't be
expanded to accommodate more data or cannot be reduced to accommodate
less data.In this case once the memorey is allocated it is fixed.
Example : array
Disadvantages:
1. Leads to
underutilization if more memorey space is allocated.
2. Leads to overflow
if les memorey is allocated.
2.Dynamic Memorey
Allocation:It is a process of allocating memorey space during
execution ti,e. This allocation technique uses predefined functions
to allocate and release memorey for data during execution time.
Various memorey
management functions:
1.malloc
2.calloc
3.realloc
4.free
1.malloc()
This function
allocates the memorey during run time.
Syntax:
data_type *p;
p=(data_type*)malloc(size);
Write a program to
show the usage of malloc
#include<stdio.h>
void main()
{
int *p1, *p2;
int sum;
p1=(int*)malloc(sizeof(int));
p2=(int*)malloc(sizeof(int));
*p1=10;
*p2=20;
sum=*p1 + *p2;
printf(“sum=%d”,sum);
}
2.calloc()
Allocates the
required memorey size during execution timeand automatically
initialize memorey with 0's.
Syntax:
data_type *p;
p=(data_type*)calloc(n,size);
What will happen if the following program segment is executed ??
int *ptr;
p=(int*)calloc(5,sizeof(int));
Case 1: if the sufficient memorey is avaliable then memorey is allocated.
Concider the
following memorey map:
p=(int*)calloc(5,sizeof(int));
execution of this
instruction will allocate the 5 blocks of memorey as the free memorey
is avaliable.
Case2: if the
sufficient memorey is not avaliable then memorey will not be
allocated.
Concider the
following memorey map:
p=(int*)calloc(5,sizeof(int));
execution of this
instruction will return NULL since there is no sufficient memorey is
avaliable.
3.realloc()
Changes the memorey
size during execution time as required.
Syntax:
data_type *p;
p=(data_type*)calloc(ptr,size);
No comments:
Post a Comment