Dynamic memory allocation in C

Preview
You must first complete Introduction to pointer in C | pointer operations in C before viewing this Lesson

Dynamic memory allocation in C

We can dynamically allocate and de-allocate memory to variables in C language.  Different functions for dynamic memory allocation/de-allocation are:

  • malloc()
  • free()




1. malloc() function

malloc() is a predefined function of C language that can dynamically allocate memory to variables. It allocates a block of fixed size block from memory. Header file required for malloc() function is stdlib.h.

Example
int *ptr;
ptr=malloc(sizeof(int));

ptr is a pointer that is allocated memory of 2 because sizeof(int) is assumed to return 2 bytes.

Program of malloc().
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr;ptr = malloc(sizeof(int));
*ptr=5;

printf(“*ptr=%d”,*ptr);
free(ptr);
}

Output
*s=15

2. free() function

This function is used to deallocate memory dyanamically assigned to a variable by using malloc() function.

Example:
free(ptr);

This command will dealloacte memory assigned to pointer variable ptr. It has been demonstrated in above program.

Best Books of C





Lesson tags: calloc() function in c, dynamic memory allocation in c, dynamic memory deallocation in c, free() function in c, malloc() function in c, memory leak in c, program of dynamic memory allocation in c, program of dynamic memory deallocation in c
Back to: C Programming Language