MEMORY ALLOCATIONS IN C
There are two types of memory
allocations possible in C.
1) Compile-time or Static allocation(using
arrays).
2) Run-time or Dynamic allocation (using
pointers).
In
the first type of allocation i.e. .static, the required amount of memory is
allocated to the program element (identifiers names which include variables
name, function name, program name etc) at the start of the program. Here the
memory to be allocated to the variable is fixed and is determined by the
compiler at the compile time (if it is a single integer variable it allocates
two bytes to it, if it is an array of five integer values it allocates ten
bytes to it and if it is a single float type of variable compiler allocates
four bytes to it).For example, consider the following declaration:
int x,y;
float a[5];
When
the first statement is encountered, the compiler will allocate two bytes to
each variables x and y. The second statement results into the allocation of 20
bytes to the array a (5*4, where there are five elements and each element of
float type takes four bytes).
The
first problem with static allocation is that once the memory is allocated for
the elements that memory cannot be reused until we exit the program.
The
second problem with static memory allocation is that if you store less number
of elements than the number of elements for which you have declared memory,
than the rest of the memory will be wasted (i.e. it is not made available to
other applications and its status is set as allocated and not free).This leads
to the inefficient use of memory.
The
concept of Dynamic or Run-time memory allocation helps us to overcome this
problem in arrays, as well as allows us to be able to get the required chunk of
memory at run-time (or we can say as the need arises).This is best suited type
of allocation where we do not know the memory requirement in advance, which is
the case with most of real-life problems. In other words, dynamic memory
allocation gives flexibility for programmer. So it makes efficient use of memory,
by allocating the required amount of memory whenever needed, unlike static
allocation where we declare the amount to be allocated statically.
C
provides the following dynamic allocation and de-allocation functions:
I. malloc()
II. calloc()
III. free()
IV. realloc()
1.
The malloc () Function
The
malloc () function allocates a block of memory in bytes. The user should
explicitly give the block size it requires for the use. The malloc () function
is like a request to the RAM of the system to allocate memory. If the request
is granted (i.e. the malloc function stays successful in allocating memory), it
returns a pointer to the first block of that memory. By default, the type of
pointer it returns is void. However if the malloc () function fails to allocate
the required amount of memory, it returns a NULL. The malloc () function is
available in header file alloc.h or stdlib.h in TURBO C, and on UNIX it will be
available in header file <malloc.h>.The syntax of this function is as
follows:
malloc (number of elements *
size of each element)
For
example,
int *ptr;
ptr= malloc(10*sizeof(int))
But
the function malloc () returns a void pointer so a cast operator is required to
change the returned pointer type according to our need, the above declaration
would take the following form:
ptr_var= (type_cast*) malloc
(size)
Where ptr_var is the name of pointer
that holds the starting address of allocated memory block, type_cast is the
data type into which the returned pointer (type void) is to be converted, and
size specifies the size of allocated memory block in bytes.
For example,
int *ptr;
ptr=(int *)
malloc(10*sizeof(int));
After
the execution of this statement, a consecutive memory block of 20 bytes is
allocated to the program. Then the starting address of the memory block is
assigned to ptr.
Similarly
for the allocation of memory to a character variable, the following statements
are required:
char
*ptr;
ptr=(char
*)malloc(10*sizeof(char))
After
the execution of above statement, a memory block of 10 bytes is allocated to
the program. The starting address of this block is assigned to ptr.
1.
Program to demonstrate the use of Dynamic memory allocation function
malloc().This program finds the sum and average of all elements of the array
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
#define
NULL 0
void
main()
{
int *ptr;
int i,n,sum=0;
float avg;
clrscr();
printf("Enter the number of
element you want to store");
scanf("%d”,&n);
ptr=(int *) malloc(n*sizeof(int));
if(ptr==NULL)
{
printf ("The required
amount of memory is not available");
getch();
exit(0);
}
else
{
printf("Enter the
elements\n");
for(i=0;i<n;i++)
scanf("%d",ptr+i);
for(i=0;i<n;i++)
{
sum=sum+(*(ptr+i));
}
printf("Sum of %d elements
of array is=%d",n,sum);
avg=sum/n;
printf("The average of %d
number of the array is %f",n,avg);
}
getch();
}
The
output of the above program will be:
Enter
the number of elements you want to store 5
Enter
the elements 22 34 1 45 6
Sum
of 5 elements is = 108
Average
of 5 elements is = 21.6
2.The
calloc() Function
This function works exactly similar to
malloc () function except that it needs two arguments as against one argument
required by malloc().
The calloc() function is available in
header file <alloc.h> or stdlib.h in TURBO C,and on UNIX it will be
available in header file <malloc.h>.
For
example:
int *ptr;
ptr=(int *) calloc(10,2);
Here 10 specifies the number of
elements for which allocation is to be made and 2 specifies the size of data
type in byte for which we want the allocation to be made, which in this case is
2 for integers.
After the execution of the above
statement a memory block of 20 bytes is allocated to the program and the
starting address of memory block is assigned to pointer ptr.
3.
The Free() function
The free() function is used to
de-allocate the previously allocated memory using malloc() or calloc()
functions. The syntax of this function is:
free(ptr_var);
Where ptr_var is the pointer in which
the address of the allocated memory block is assigned. The free function is
used to return the allocated memory to the system RAM.
The malloc() function allocates
memory, and the free() function releases it.
Each time malloc() memory request is
made, a portion of the remaining free memory is allocated.
Each time a free() memory releases
call is made, memory is returned to the system.
4.
The realloc() function
This function is used to resize the
size of memory block, which is already allocated(i.e. to modify the size of
already allocated memory block).it is mainly used in two situations:
I. if the allocated memory block is
insufficient for current application
II. if the allocated memory is much more
than what is required by the current application.
The
syntax of this function is as follows:
ptr_var=realloc(ptr_var,new_size);
Where
ptr_var is the pointer holding the starting address of already allocated memory
block. And new_size is the size in bytes you want the system to allocate now,
it may be smaller than the size of previously allocated memory block or may be
greater than the size of previously allocated memory block depending upon the
requirement. This function is also available in the header file <alloc.h>
and <stdlib.h>
Note:
Before using the realloc() function, the memory block to be resized should be
allocated, using the following statement:
Ptr_var=malloc(size);
2.
Program to illustrate the use of functions realloc() and free()
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<alloc.h>
void
main()
{
char *msg;
clrscr();
msg=(char *) malloc(10*sizeof(char));
strcpy(msg, "My name is");
printf("The message now is
%s\n",msg);
msg=(char *) realloc(msg,25);
strcpy(msg,"My name is Raul
Gonzaalez");
printf("\n The message is now
%s",msg);
free(msg);
getch();
}
0 Comments
Please Don't Post Spam Links Under Comment Section.