Dynamic Memory Allocation in C

C programming language allows dynamic memory allocation. It means that the user can allocate and deallocate the memory at runtime. For allocating and deallocating memory c provides four functions namely malloc, calloc , realloc and free.

How to use malloc() function ?

malloc() function is used to allocate a continuous block of memory of specified size in bytes. If space in heap is not sufficient to satisfy the request then the allocation fails and malloc() function returns NULL.

Syntax:

// remember the cast-type must be same as of pointer ptr
ptr=(cast-type *)malloc(size);

Example:

int *ptr;
ptr=(int *)malloc(10* sizeof(int));
Above example allocates 10 memory locations each of size equivalent to the size of integer type in system being used. For a 32 bit system it will allocate 10 memory locations each of size 4 bytes.

How to use calloc() function ?

calloc() functions works just like malloc() function but with one additional feature that it initializes the memory allocated to 0.

Syntax:

// remember for calloc also the cast-type must be same as of pointer ptr
ptr=(cast-type *)calloc(size);

Example:


int *ptr;
ptr=(int *)calloc(10* sizeof(int));

Above example allocate 10 memory locations as well as initializes them to 0.

How to use realloc() function ?

realloc() function is used to increase or decrease the memory size.

Syntax:

ptr=realloc(ptr,new-size)

Example:

int *ptr;
ptr=(int *)malloc(10* sizeof(int)); // allocating memory for 10 integers
ptr=realloc(ptr,20*sizeof(int)); // allocating memory for 10 more integers
ptr=realloc(ptr,10*sizeof(int)); // deallocating memory for 10 more integers
Above example allocates memory for 10 integers using malloc() function and then allocates memory for 10 more locations that it reallocates memory for total 20 locations using realloc() function. Finally it also deallocates 10 memory locations.

How to use free() function ?

free() function is used to deallocate memory and returns it to the heap so that it can be used for other purposes.

Syntax:

free(ptr-name);

Example:

int *ptr;
ptr=(int *)malloc(10* sizeof(int)); // allocating memory for 10 integers
free(ptr);
Above examples deallocates the memory previously allocated by malloc() function for 10 integers.