Dynamic Memory Allocation: UNIT-1
Dynamic Memory Allocation: UNIT-1
Dynamic Memory Allocation: UNIT-1
Many languages permit a programmer to specify an array’s size at run time. Such languages
have the ability to calculate and assign, during execution, the memory space required by the
variables in the program.
Function Description
malloc() Allocates requested size of bytes and returns a void pointer pointing to
the first byte of allocated space.
calloc() Allocates the space for an array element’s, initializes them to zero and
then returns a void pointer to the memory.
realloc() Modify the size of previously allocated space.
free() Release previously allocated memory.
Memory allocation process
Local variables
Free memory
Global variables
C program
instructions
Storage of c program
The program instructions, global and static variables are stored in a region known as
permanent storage area and the local variables are stored in another area called stack.
The memory space that is located between these two regions is available for dynamic
allocation during execution of the program. This free memory region is called the
heap. The size of the heap keeps changing when program is executed due to creation
and death of variables that are local to functions and blocks. Therefore, it is possible to
encounter memory overflow during dynamic allocation process. In such situations, the
memory allocation functions returns NULL pointer.
OR
pointer variable=(cast-type*)malloc(byte-size);
Pointer variable is of a type cast- type. The malloc returns a pointer to an area of
memory with size byte-size.
Example:
x=(int)malloc(100*sizeof(int));
The above example allocates 100 times the size of an integer bytes is reserved and the
address of the first byte of the memory allocated is assigned to the pointer of x of type
int.
cptr=(char*)malloc(10);
We can also use malloc() to allocate space for complex data types such as structures.
#include<stdio.h>
#include<stdlib.h>
void main()
int *ptr,sum=0,*a;
int n;
scanf(“%d”,&n);
exit(0);
}
printf(“Enter the elements one by one\n”);
scanf(“%d”,a);
printf(“%d”,*a);
sum=sum+a;
OUTPUT:
10
20
30
40
50
20
30
40
50
Sum=150
The above illustrates the sum of n numbers in an array. Here the memory allocation is
done using malloc (). The allocated memory is equal to the n times the size of an
integer.
If the memory allocation fails due to the insufficient space in heap ,malloc () function
returns NULL otherwise the variable ptr contains the address of the first byte of the
allocated memory.
The values are read one by to the location which is pointed by ptr .The value of ptr is
assigned to another pointer variable ‘a’ .Values are read from into the address of the
first location till (p+n-1)th location’s address .Each time the value of the pointer is
incremented by scalar factor. Value pointed by the pointer ‘ptr’ is made to pointed by
the pointer ‘a’. These values are added till (p+n-1)th location. Finally the value of sum
is displayed.
3. With an example explain how to allocate multiple block of memory (10 marks)
OR
pointer_variable=(cast-type *)calloc(n,elem-size);
The above statement allocates contiguous space for n blocks, each of size elem-size
bytes. All bytes are initialized to zero.
Parameter:
It takes two parameters one is the value n ,which the number of elements for which
you want to allocate memory and elem-size is the size of each element in bytes.
Return value: On success a pointer to the first byte of the allocated region is
returned. If there is no enough space, a NULL is returned.
Example:
p=(int *)calloc(5,sizeof(int));
In the above example 5 blocks of memory is allocated each of size 2 bytes .Assuming
an integer occupies 2 bytes of memory. It returns void pointer by default it is
converted integer pointer as the type of pointer variable p is integer.
Example:
#include<stdio.h>
void main()
int *p,*a;
int n;
printf(“Enter the number of elements for which you want to allocate memory\n”);
scanf(“%d”,&n);
a=(int*)calloc(n,sizeof(int));
for(p=a;p<a+n;p++)
scanf(“%d”,p);
for(p=a;p<a+n;p++)
printf(“%d\n”,*p);
for(p=a;p<a+n;p++)
{
if(*p%2==0)
printf(“%d is even\n”,*p);
else
printf(“%d is odd\n”,*p);
free(p);
OUTPUT:
Enter the number of elements for which you want to allocate memory
2 is even
3 is odd
5 is odd
4 is even
The above example shows the memory allocation using calloc().The function calloc()
allocates memory dynamically, the allocated memory is 5 block each of the size 2
bytes. The address of the first block of the allocated memory is stored in a pointer
variable a.
Using loop n values are read into a pointer variable. Each time it is incremented by
one so that it points to the next location.
Each values are accessed from the address of the first block till the address of the
p+n-1 blocks. When each block is accessed its values are checked to find whether the
number is even or odd.
calloc() can be also used to allocate memory space for structure. Here the memory is
allocated for the individual memory of structure using number of records you want to
store and the size of the structure.
int s_size=5;
ptr=(stu*)calloc(s_size,sizeof(stu));
In the above example pointer ptr is of type structure tag name. It allocates total block
which is equal to the number of records you are storing and each of the size stu.
Example:
#include<stdio.h>
#include<stdlib.h>
struct student
char name[10];
float tmarks;
int regno
};
stu *ptr;
void main()
{
int s_size;
stu ptr;
scanf(“%d”,&s_size);
ptr=(stu*)calloc(s_size,sizeof(stu));
if(ptr==NULL)
exit(0);
for(i=0;i<s_size;i++)
scanf(“%s%d%f”,p->name,&(p->marks),&(p->regno));
for(i=0;i<s_size;i++)
printf(“%s%d%f”,p->name,p->marks),p->regno);
OR
When a variable is allocated space during the compile time, then the memory used by
that variable is automatically released by the system in accordance with its storage
class. But when we dynamically allocate memory then it is our responsibility to
release the space when it is not required. This is even more important when the
storage space is limited. Therefore, if we no longer need the data stored in a particular
block of memory then it is our responsibility to release that block for storing any other
information, then as a good programming practice we must release that block of
memory for future use, using the free function.
General form:
free(pointer variable);
Pointer variable is a pointer that has been created by using malloc() or calloc().When
the memory is released using the free, it is returned back to the free list within heap.
i) It is not the pointer that is being released but rather what it points to.
ii) To release an array of memory that was allocated by calloc() we need only
to release the pointer once. It is an error to attempt to release elements
individually.
Example:
#include<stdio.h>
#include<stdlib.h>
void main()
char *str,*str1;
str=(char*)malloc(10*sizeof(char));
str1=(char*)calloc(10,sizeof(char));
if(str==NULL)
exit(0);
gets(str);
strcpy(str1,str);
printf(“content of str is %s”,str);
free(str);
free(str1);
OUTPUT:
allocation
In the above example ,10 memory locations are allocated using malloc for the string
str each of the size one byte. The string str contains the address of the first byte of the
allocated space. Also for the memory is allocated for the destination string str1 using
calloc() total 10 blocks of memory is allocated and each of the size 1 byte.The string
str1 contains the address of the first block of the allocated memory in bytes.Both the
function returns NULL if there is insufficient memory .
User enters a string from the console, which is pointed by the pointer str. Content of
str is copied to str1 using string copy function strcpy().
At the end content of both the files are displayed and allocated memory for the string
str and str1 is released using free ().
Advantages of free():
OR
The function realloc() reallocates a memory block with a specified new size.If you call
realloc() the size of the memory block pointed to by the pointer is changed to the
given size in bytes.This way you are able to expand and reduce the amount of memory
you want to use.
It is possible that the function moves the meory block to anew location, in which the
function will return new location.
If the size of the requested block is larger then the previous block then the value of the
new portion is intermediate.
If the pointer is NULL then the function will behave exactly like the function
malloc().It will assign a new block of a size in bytes and will return a pointer to it.If
the size is zero then the memory that was previously allocated is freeds or if a call to
the function free()was given it returns a NULL pointer in that case.
Syntax:
Parameter: This function takes two parameter one is pointer and another one is new
size.
Return value: Will return a pointer to the reallocated memory block.If the function
fails then a NULL pointer is returned.
Example:
(int *)realloc(ptr,30);
Using realloc we are changing the size of the memory .ptr is a pointer variable which
is pointing to the previously allocated memory using malloc() or calloc().The size of
the allocated block is changed to 30 which is a new size for the memory after realloc.
Example:
#include<stdio.h>
#include<stdlib.h>
void main()
char *buffer;
scanf(“%d”,&n);
buffer=(char *)malloc(n,sizeof(int));
if(p==NULL)
exit(0);
strcpy(buffer,”data”);
buffer=(char*)realloc(buffer,15);
if(buffer==NULL)
printf(“reallocation failed\n”);
exit(0);
}
printf(“Buffer size modified\n”);
strcpy(buffer,”structure”);
free(buffer);
Output:
The above example illustrates the use of realloc() for changing the allocated memory
during run time.At the beginning memory is allocated using malloc().We can also
allocate using realloc().It return NULL if there is insufficient memory otherwise it
returns the address of the first byte of the allocated space.
Value of ‘n’ is read from the user ,which is the number of memory locations to be
allocated using malloc().The pointer variable buffer contains the address of the first
byte of the allocated space.It contains NULL where there is insufficient space on the
heap.Number of the bytes allocated or pointed by the pointer buffer can be calculated
using _msize() function which is defined in the library <stdlib.h>.
Data “data” is copied to the location which is pointed by the pointer buffer.
Memory for the pointer buffer is reallocated using realloc().The address of the
previously allocated space and the new size 15 is passed to it.Now the size of the
allocated space is changed from 10 to 15. Data “structure” is copied to the reallocated
space.Pointer buffer contains the new data structure.
malloc() calloc()
It allocates only single block of requested It allocates multiple block of requested
memory memory
malloc() does not initializes the allocated calloc() initializes the allocated memory
memory to zero. It contains garbage to zero.
value.
Malloc is faster than the calloc Calloc takes little longer than malloc
because of the extra step of initializing the
allocated memory by zero.However, in
practice the difference in speed is very
tiny and not recognizable.
void * malloc(n).Allocates n bytes of void *calloc(n,sizeof(type));
memiory .If the allocation succeeds ,a Allocates a continuous block of memory
void pointer is to the allocated memory is large enough to hold n elements of size
returned. Otherwise NULL is returned. bytes each.The allocated region is
The pointer contains the address of the initialized to zero. The pointer contains
first byte of the allocated space. the address of the first block of the
allocated space.
Example: Example:
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int *a,*p,n; int *a,*p,n;
printf(“Enter n\n”); printf(“Enter n\n”);
scanf(“%d”,&n); scanf(“%d”,&n);
p=(int*)malloc(n*sizeof(int)); p=(int*)calloc(n,sizeof(int));
for(a=p;a<(p+n);a++) for(a=p;a<(p+n);a++)
scanf(“%d”,a); scanf(“%d”,a);
for(a=p;a<(p+n);a++) for(a=p;a<(p+n);a++)
printf(“%d\n”,a); printf(“%d\n”,a);
} }
Malloc() can one parameter or two. Calloc() always takes two parameters
#include<stdio.h>
#include<stdlib.h>
void main()
int n,*p,i,j,temp;
scanf(“%d”,&n);
p=(int *)malloc(n*sizeof(int));
if(fp==NULL)
exit(0);
for(a=p;a<p+n;a++)
scanf(“%d”,a);
for(i=0;i<a+n;i++)
for(j=0;i<n;j++)
if(*(p+i)<*(p+j))
temp=*(p+i);
*(p+i)=*(p+j);
*(p+j)=temp;
for (a=p;a<p+n;a++)
printf(“%d\n”,*a)’
OUTPUT:
14
16
4
The sorted array using malloc is :
14
16
A block of memory can be allocated using the function malloc().The malloc function
reserves a block of memory specified size and returns a pointer of the type void.It can
be converted to any of the type by specifying as cast-type.
Example:
float *avg;
avg=(float*)malloc(n*sizeof(float));
The above example allocates the memory for the variable avg of type float.The
allocated memory is equal to the n times the size of float and the address of the first
byte of the memory is assigned the pointer avg of type float.
#include<stdio.h>
#include<stdlib.h>
void main()
int *ptr,sum=0,*a;
int n;
scanf(“%d”,&n);
exit(0);
scanf(“%d”,a);
printf(“%d”,*a);
sum=sum+a;
OUTPUT:
10
20
30
40
50
10
20
30
40
50
Sum=150
The above illustrates the sum of n numbers in an array. Here the memory allocation is
done using malloc (). The allocated memory is equal to the n times the size of an
integer.
If the memory allocation fails due to the insufficient space in heap ,malloc () function
returns NULL otherwise the variable ptr contains the address of the first byte of the
allocated memory.
The values are read one by to the location which is pointed by ptr .The value of ptr is
assigned to another pointer variable ‘a’ .Values are read from into the address of the
first location till (p+n-1)th location’s address .Each time the value of the pointer is
incremented by scalar factor. Value pointed by the pointer ‘ptr’ is made to pointed by
the pointer ‘a’. These values are added till (p+n-1)th location. Finally the value of sum
is displayed.
#include<stdio.h>
#include<stdlib.h>
void main()
{
int *p,*a;
int fact,n,m;
scanf(“%d”,&n);
p=(int*)calloc(n,sizeof(int));
if(p==NULL)
printf(“Insufficient memory\n”);
exit(0);
for(a=p;a<p+n;a++)
scanf(“%d”,a);
for(a=p;a<p+n;a++)
printf(“%d\n”,*a);
for(a=p;a<p+n;a++)
fact=1;
for(m=1;m<=*a;m++)
fact=fact*m;
printf(“factorial of %d is %d\n”,*a,fact);
OUTPUT:
Enter the number of elements into an array
Factorial of 4 is 24
Factorial of 2 is 4
Factorial of 3 is 6
The above example illustrates the use of calloc() for dynamic memory alloacation.
The value is ‘n’ is received from the user which is the number blocks you want to
allocate. Total ‘n’ blocks of memory is allocated each of two bytes. On success the
address of the first region or block is stored in the pointer variable p otherwise it
returns NULL. The value at p is assigned to the pointer variable a. The address stored
in the pointer p is assigned to a. The values are read into the starting address till (p+n-
1)th address into the location using pointer variable a. Each time the value of ‘a’ is
increment by the scalar factor*1.
The each value from the blocks are accessed through the pointer ‘a’ when we access
new block the variable fact is set to 1.Factorial of each elements from the block are
calculated using fact=fact*m. Factorial loop is initialized to the starting value 1 till it
reaches the value pointed by the pointer a. Finally the value of fact is displayed. This
process continues till we access the value of (p+n-1)th block.
#include<stdio.h>
#include<stdlib.h>
void main()
int *p,*a;
int i,n;
chat ch;
scanf(“%d”,&n);
p=(int *)calloc(n,sizeof(int));
for(a=p;a<p+n;a++)
scanf(“%d”,a);
scanf(“%c”,&ch);
if(ch==’y’)
scanf(“%d”,&n);
p=(int*)realloc(p,n);
for(a=p;a<p+n;a++)
scanf(“%d”,a);
for(a=p;a<p+n;a++)
sum=sum+*a;
printf(“%d\n”,sum);
}
OUTPUT:
Sum=21
The above example illustrates the use of realloc() for changing the allocated memory
using calloc() or malloc().The number of memory locations for storing array elements
is allocated using calloc().Total ‘n’ locations are allocated each of the size 2 bytes.
The pointer variable ‘p’ has the address of the first memory space which is allocated
using calloc().Elemnts to the allocated space are entered starting from the first space
address till (p+n-1)th address.
If the user don’t want to alter the memory then the character ’n’ is entered otherwise
the character ‘y’ is pressed .User enters new size to reallocate and the address of the
first byte which is allocated busing calloc().New elements are entered. Sum of all the
elements from the address of the first byte till (p+n-1) byte are calculated.
i)malloc():Allocates requested size of bytes and returns a void pointer pointing to the
first byte of allocated space.
ii)calloc():Allocates the space for an array element’s, initializes them to zero and then
returns a void pointer to the memory.
i) Malloc():
A block of memory can be allocated using the function malloc.
The malloc() function reserves a block of memory of specified size and returns
a pointer of type void. This means that we can assign it to any type of pointer.
malloc() does not initialize the memory allocated during the execution. It
carries garbage value
Syntax:
pointer variable=(cast-type*)malloc(byte-size);
Pointer variable is of a type cast- type. The malloc returns a pointer to an area of
memory with size byte-size.
Example:
x=(int)malloc(100*sizeof(int));
The above example allocates 100 times the size of an integer bytes is reserved and the
address of the first byte of the memory allocated is assigned to the pointer of x of type
int.
We can also use malloc() to allocate space for complex data types such as structures.
ii)Calloc():
calloc() is used for requesting memory space at run time for storing derived data types
such as arrays and structures. While malloc() allocates a single block of memory of
storage space , calloc allocates multiple blocks of storage, each of the same size and
then sets all bytes to zero.
pointer_variable=(cast-type *)calloc(n,elem-size);
The above statement allocates contiguous space for n blocks, each of size elem-size
bytes. All bytes are initialized to zero.
Parameter:
It takes two parameters one is the value n ,which the number of elements for which
you want to allocate memory and elem-size is the size of each element in bytes.
Return value: On success a pointer to the first byte of the allocated region is
returned. If there is no enough space, a NULL is returned.
Example:
p=(int *)calloc(5,sizeof(int));
In the above example 5 blocks of memory is allocated each of size 2 bytes .Assuming
an integer occupies 2 bytes of memory. It returns void pointer by default it is
converted integer pointer as the type of pointer variable p is integer.
iii)realloc():
It is possible that the function moves the meory block to anew location, in which the
function will return new location.
If the size of the requested block is larger then the previous block then the value of the
new portion is intermediate.
If the pointer is NULL then the function will behave exactly like the function
malloc().It will assign a new block of a size in bytes and will return a pointer to it.If
the size is zero then the memory that was previously allocated is freeds or if a call to
the function free()was given it returns a NULL pointer in that case.
Syntax:
Parameter: This function takes two parameter one is pointer and another one is new
size.
Return value: Will return a pointer to the reallocated memory block.If the function
fails then a NULL pointer is returned.
Example:
(int *)realloc(ptr,30);
Using realloc we are changing the size of the memory .ptr is a pointer variable which
is pointing to the previously allocated memory using malloc() or calloc().The size of
the allocated block is changed to 30 which is a new size for the memory after realloc.
Example program:
#include<stdio.h>
void main()
char ch;
int *p,*a;
int n;
scanf(“%c”,&ch);
switch(ch)
case ‘m’:
p=(int*)malloc(n*sizeof(int));
for(a=p;a<(p+n);a++)
scanf(“%d”,a);
for(a=p;a<(p+n);a++)
printf(“%d\n”,a);
break;
case ‘c’:
p=(int*)calloc(n,sizeof(int));
for(a=p;a<(p+n);a++)
scanf(“%d”,a);
for(a=p;a<(p+n);a++)
printf(“%d\n”,a);
break;
case ‘r’:
p=(int*)calloc(n,sizeof(int));
for(a=p;a<(p+n);a++)
scanf(“%d”,a);
scanf(“%c”,&ch);
if(ch==’y’)
Scanf(“%d”,&n);
p=(int*)realloc(p,n);
for(a=p;a<(p+n);a++)
scanf(“%d”,a);
for(a=p;a<(p+n);a++)
printf(“%d\n”,a);
break;
default:printf(“Invalid choice\n”);
break;
Question bank
5 marks questions
4. With an example explain how to alter the size of previously allocated space.
10 marks questions
6. How are static and dynamic memory allocations different? Write a program to
sort 10 numbers using malloc().