Dynamic Memory Allocation  in C with Example

Dynamic memory allocation refers to the manual memory management in the C language.

Need of Manual Memory Management/ Dynamic Memory Allocation :

  • In case of array, the programmer must declare the size of the array during compile time (the time when a compiler compiles code written in a programming language into executable form).
  • But consider a situation in which the programmer do not have any idea about the length/size of the array to define.
  • In that case the size of the array he declared the size either insufficient or more than he required.
  • In the first case, the compiler stops the program due to insufficient space and in the latter case, there is a wastage of space.
  • Since the exact size of array is unknown, the programmer needs dynamic memory allocation.

A brief description on Memory layout of C programs

C facilitate dynamic memory allocation. Let us understand how C organizes memory for its programs. After compiling a program, creates distinct regions of memory that are used for different distinct specific functions. These regions are :

  1. Program code segment/region
  2. Data segment/region
    1. Initialised data or data segment
    2. Uninitialised data or .bss segment
  3. Stack region
  4. Heap region

Dynamic Memory Allocation

Regions :

Program Code Region :

This region in the memory holds the combined code of the program. The program’s every instruction and the program’s every function starts at a particular address.

Data Segment :

Data segment stores program data and it could be in any form like initialised or uninitialised variable, local or global variables. Data segment is further divided into

  1. Initialised data or data segment : It stores all initialised :
    • Global variables( including Global static variables)
    • Static local variables
    • Constant
    • External variables
  2. Uninitialised data or .bss segment : It stores all uninitialised :
    • Global variable
    • Static variable
    • External variable

    The Data is initialised to arithmetic 0(zero) by the kernel in this segment before the program starts executing.

    For example,

    static int i;    // This variable would be in .bss segment
    int j;          /* j is globally declared. and therefore it
                       would also be in .bss segment */
Stack Region :

This region is used for great many things while your program executes. The stack holds :

  • return addresses at function calls
  • arguments passed to the functions
  • and local variables for functions. These variables remain in memory as long as the function continues and after that they are erased from the memory.
  • It also stores the current state of the CPU.
Heap Memory Region :
  • The heap memory area is a region of free memory from which chunks of memory allocated via C dynamic memory allocation functions.
  • It contains a linked list of used and free blocks.
  • Free blocks is dynamically allocated during run time and static memory allocation takes place during compile time. This requires a meta information about the blocks on the heap, which is stored in front of every block so to keep an eye on available/free blocks.

To know more about memory layout in C – Click here.
To know about memory layout of C++ – Click Here.

Dynamic Memory Functions of C :

The C dynamic memory allocation functions are defined in stdlib.h header.

Function Description  Syntax :
malloc() allocates the specified number of bytes void *malloc(int num);
realloc() increases or decreases the size of the specified block of memory. Reallocates it if needed void *realloc(void *address, int newsize);
calloc() allocates the specified number of bytes and initializes them to zero void *calloc(int num, int size);
free() releases the specified block of memory back to the system void free(void *address);

C malloc() Function :

  • malloc() function is used to allocate space in memory during the execution of the programme.
  • malloc() does not initialise allocated memory during run time. It carries garbage value.
  • malloc() function returns null pointer if it could not able to allocate requested amount of memory.
  • malloc() stands for memory allocation.
Syntax of malloc() Function :
p = (cast-type*)malloc(byte-size)

Here, p is pointer of cast-type. The malloc() function returns the address of the allocated memory to the pointer with size of byte-size. When the space is not enough, allocation fails and returns NULL pointer.

p = (int*)malloc(100*sizeof(int));

This statement will allocate 200 bytes in a 16 bit processor system and the pointer p points to the address of first byte of memory.

C calloc() Function :

  • The calloc() function stands for contiguous allocation of memory.
  • It is just like like malloc() function with a difference that calloc() initialises the allocated memory to 0(zero), but malloc doesn’t.
Syntax of calloc() :
p = (cast-type*)calloc(n,element-size);

Here, p is pointer of cast-type. The calloc() function allocates with contiguous space in memory and returns the address of the allocated memory to the pointer p with size of byte-size. If the space is insufficient, allocation fails and returns NULL pointer.

p = (float*)calloc(25,sizeof(float));

This statement creates an array of 25 elements each of size of float, i.e, 4 bytes in a 16 bit processor system. In other words, the above statement allocates contiguous space in memory for 25 elements each of size 4 bytes

Difference between calloc() and malloc() function :

Basis malloc() calloc()
Number of Blocks Allocate It allocates only single block of requested memory It allocates multiple blocks of requested memory
Example : int *p; p = malloc(10*sizeof(int)); ⇒ 10*2 = 20 bytes of memory only allocated in one block. int *p; p = calloc(10, 10 * sizeof(int) );
10 blocks of memory will be created and each block is of 10*2 = 20 bytes.
Therefore total memory occupied = 20*10 = 200 bytes
Initialization of Allocated Memory malloc () does not initializes the allocated memory during runtime. It contains garbage values calloc () initializes the allocated memory to zero
Type-casting is necessary in both functions type cast must be done since this function returns void pointer
int *p;
Same as malloc () function.
int *p;
p=(int*)calloc( 10, 10*sizeof(int));
Number of Arguments malloc() takes a single argument( the amount of memory to allocate in bytes). calloc() needs 2 arguments( the number of variables to allocate memory, and the size in bytes of a single variable).

C realloc() Function :

  • realloc() stands for reallocation of allocated memory.
  • This function modifies memory allocated by malloc() and calloc() functions to new size.
  • Reallocation is necessary in the case if the previously allocated memory is more than sufficient or insufficient.
  • If during relocation, enough space does not exist in memory to extend the current block, then
    • Step 1 : A new block is allocated for the full size of relocation,
    • Step 2 : Copies the existing data to the new block and
    • Step 3 : Frees the old block.
Syntax of realloc() Function :
p = realloc(p,new_size);

Here,  pointer p is reallocated with size of new_size.

C free() Function :

  • When the program no longer needs the dynamically allocated objects allocated with either calloc(), malloc() or realloc(), the it must be freed, because they remains in memory even the program stops. So, It is explicitly removed by the programmer using free() function.
  • free () function frees/deallocate the allocated memory and returns the memory to the system.
  • The space freed by the free() function, guarantee that there is no data remains impaired. Therefore you cannot access the same area once released.
Syntax of free() Function

This statement cause the space in memory pointer by p to be deallocated.

Example of malloc(), calloc(), realloc() and free() functions :

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
     char *m,*c;
     m = (char*)malloc(8*sizeof(char));
     c = (char*)calloc(1,8*(sizeof(char)));
     if(m==NULL && c==NULL )
         printf("Couldn't able to allocate requested memory\n");
        printf("\n malloc() initial initialization value = %d (some garbage value)", *m);
        printf("\n calloc() initial initialization value = %d (always)", *c);
        strcpy(m, "edugrabs");
        strcpy(c, "edugrabs");
     printf("\nContent of Dynamically allocated memory by malloc: %s",m);
     printf("\nContent of Dynamically allocated memory by calloc: %s",c);
     m = realloc(m,15*sizeof(char));
         printf("Couldn't able to reallocate requested memory\n");
     printf("\nContent of Dynamically reallocated memory by realloc: %s",m);
     return 0;
Output :
malloc() initial initialization value = 42    (some garbage value)
calloc() initial initialization value = 0     (always)
Content of Dynamically allocated memory by malloc  : edugrabs
Content of Dynamically allocated memory by calloc  : edugrabs
Content of Dynamically allocated memory by realloc : edugrabs.com

Incoming search terms:

  • dynamic memory allocation in c with example- edugrabs
  • dynamic memory allocation in c programming examples
  • examples of static and dynamic memory
  • What are the dynamic memory allocation function?example suitable diagram

Leave a Reply