Memory Allocation Systems In C Language
The C language supports two kinds of memory allocation through the variables in C programs :
1. Static allocation
2. Dynamic allocation

Static allocation :

If size or count of variables is known at coding time then static allocation is the good choice, the static system is managed by the compiler by adding necessary instructions in the program for allocation/de-allocation of memory for variables. So programmer need not bother how variables are created and destroyed in the program.
Static allocation is what happens when you declare a static or global variable. Each static or global variable defines one block of space, of a fixed size. The space is allocated once, when your program is started (part of the exec operation), and is never freed.

Dynamic allocation :

In many real systems, the size of memory and objects are not known and cannot be determined until runtime. Here dynamic system is the alternative to the programmer. Dynamic allocation refers to the allocation of such memory during program execution. Here programmer needs to allocate & de-allocate the memory with the help of pointers.

This dynamic memory allocation system provides us to create, expand, reduce, or even destroy the memory at runtime. This feature is very much useful for efficient memory management especially while handling huge collection of data using “data structures” for example lists, stacks, trees, graphs.

To work with this feature, C provides the following built-in functions :

       1. malloc()
       2. calloc()
       3. realloc()
       4. free() 

1.malloc() :
The name malloc stands for "memory allocation". It allocates memory of required size and returns the address of starting byte (base address). In this allocation raw memory, we can store any type of data such as int, long, float, double, char, etc. So malloc() returns an address which has no type. That is, it returns ‘void*’ type address called generic address. Unfortunately, if memory is not available then malloc() or other functions returns NULL value.

Syntax    :      void* malloc(int num)

Example : pointer=malloc(no of bytes to be allocated);

In the above example, the function malloc() allocates 10 bytes of memory in the RAM and returns the starting byte address, which is then assigned to ‘p’. Suppose if we are going to store array of integers then the pointer should be ‘int*’ type. malloc() returns just address which has no type, that is it returns ‘void*’ type address. So it should be type casted as per our pointer type.(All malloc(), calloc(), and realloc() functions return-type is void* type) 

Example : int *p;
        p= (int*)malloc(5*sizeof(int)); //Allocating memory for 5 integers

Accessing dynamic memory :
Accessing this memory is same as accessing elements in the array through pointer.

*(p+0)->p[0] accesses first location
*(p+1)->p[1] accesses second location
*(p+2)->p[2] accesses third location
*(p+ i)->p[i] accesses i+1th  location

  Program : A program for accepting ‘n’ integers and printing using dynamic memory allocation system.
void main()
  int n, i,*p;
  printf(“enter no. of input values:”);
  scanf(“%d”, &n);

   printf(“\n not enough memory”);
  for(i=0;i<n; i++)
   printf(“enter any value:”);
   scanf(“%d”, &p[i]);
printf(“values are:”);
  for(i=0;i<n; i++)
  printf(“%d”, p[i]);
Output :

Enter no. of input values: 3
Enter any value: 5
Enter any value: 10
Enter any value: 20
Values are: 5 10 20

In the above, the array created with required size of memory and assessed through pointer. Here the input size(n) can be anything and cannot be known at coding time, thus it makes efficient usage of memory.

2.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.

The calloc function allocates space for an array of items and it is also like malloc(), but after allocation of memory, it clears the garbage values by filling zeros in all bytes in the memory.

Syntax :     pointer=calloc(int num, int size);

It takes two arguments, first one is number of items to be allocated and second one is size of the item.

Example :     float *p;
                      p=(float*)calloc(5,sizeof(float));   //allocating memory for 5 float numbers

Program : The following program is an example to find sum of n elements entered by user. To perform this program, allocate memory dynamically using calloc() function.
#include <stdio.h>
#include <stdlib.h>
int main(){
int n, ,*ptr, sum=0;
printf(“Enter number of elements : “);
scanf("%d", &n);
 ptr=(int*)calloc(n, sizeof(int));
        printf(“Error! memory not allocated.”);
    printf(“Enter elements of array : “);
        scanf(“%d”, ptr+i);
        sum+=*(ptr+ i);
    printf(“Sum = %d”, sum);
    return 0;
Output :

Enter number of elements : 3
Enter elements of array : 10 20 30
Sum = 60

Difference between malloc() and calloc() functions in C : malloc() calloc()
1 It allocates only single block of requested memory It allocates multiple blocks of requested memory
2 int *ptr, ptr = malloc( 20 * sizeof(int) );For the above, 20*4 bytes of memory only allocated in one block.
Total = 80 bytes
int *ptr; Ptr = calloc( 20, 20 * sizeof(int) );For the above, 20 blocks of memory will be created and each contains 20*4 bytes of memory.
Total = 1600 bytes
3 malloc () doesn’t initializes the allocated memory. It contains garbage values calloc () initializes the allocated memory to zero
4 type cast must be done since this function returns void pointer int *ptr; ptr = (int*)malloc(sizeof(int)*20 ); Same as malloc () function int *ptr; ptr = (int*)calloc( 20, 20 * sizeof(int) );
3. realloc() :

The name realloc() stands for “reallocation”. If the previously allocated memory is insufficient or more than sufficient. Then, you can change memory size previously allocated using realloc().

It is used to resize (reduce or expand) the memory which is already allocated using “malloc()” or “calloc()” or “realloc()”. It takes base address of previously allocated memory and new size which is currently required.

While expanding the memory size using “realloc()”, if the required amount of memory is not available at the consecutive locations, then allocates memory at another available location, and copies the existing contents to the newly allocated memory area and then releases the old memory. If the memory is not available, then it returns null.

Syntax :     ptr=realloc(ptr, new size);

Program : The following program is an example of realloc().
#include <stdio.h>
#include <stdlib.h>
int main(){
    int *ptr,i,n1,n2;
    printf(“Enter size of array: “);
    printf(“Address of previously allocated memory: “);
         printf(“%u\t”, ptr+i);
    printf(“\n Enter new size of array: “);
printf(“Address of newly allocated memory:”);
         printf(“%u\t”, ptr+i);
    return 0;
Output :

Enter size of array: 3
Address of previously allocated memory: 2303024   2303028   2303032
Enter size of new array: 5
Address of newly allocated memory: 2303024   2303028   2303032  2303036   2303040

4. free() :

It is used to release the memory which is no longer required by the program. This memory must not be static(int a[10]). This must be a dynamic memory which is allocated by malloc() or other functions. It takes the base address of memory as an argument and frees.

Syntax :     void free(void *ptr);

If a null pointer is passed as argument, no action occurs. And this function does not return any value.

Program : The following program shows the usage of free().
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () {
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(20);
   strcpy(str, "freetimelearning");
   printf("String = %s,  Address = %u\n", str, str);

   /* Reallocating memory */
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);

   /* Deallocate allocated memory */
Output :

String=freetimelearning,       Address=19263504,       Address=19267648