Memory allocation Functions in c

There are two types of memory allocations in C.

  1. Static Memory Allocation 2. Dynamic Memory Allocation

  2. Static Memory Allocation: The process of allocating memory at compile time is called “static memory allocation”. The memory reserved is fixed in this and can‟t be changed during runtime.

  3. Dynamic Memory Allocation:  The process of allocating during program execution (runtime) is called Dynamic memory allocation  We change the memory allocations for each execution of a program.  This allocation avoids the wastage of memory space (which is done in arrays).

Memory allocation process

Insertion sort
  • The program instructions and global variables are stored in an area in memory called “Permanent Storage Area”.
  • The local variables stored in memory are called “Stack”.
  • The area between the stack and permanent storage is called “Heap” which is used for dynamic memory allocation.
  • Dynamic memory allocations can be done using following functions
  1. malloc

this malloc function is used allocate a single block of memory of specified size .memory allocated in the heap is accessed by pointers

syntax: ptr = (caste type *)malloc (bytesize);
  • ptr is the pointer is the pointer variable
  • case type * is data type
  • byte size is total no of bytes ,should be allocated during runtime of the program
example: int *x; c
x=(int *)malloc(15);

program example:

void main()
int n, *a,i;
printf("\nEnter the size of an array: ");
a = (int*)malloc(n);
printf("\nEnter the Elt: ");
  1. calloc
  • The function is used to allocate multiple blocks of memory/storage.
  • By default, all the locations will be initialized to zero.
  • It is specifically used to store structures.
syntax: ptr = (casttype *)calloc(n, size);

n=no. of blocks; size=no. of bytes to be allocated to each block.

  1. realloc

    This function is used to increase/decrease the size of already allocated memory.

syntax :ptr=(casttype*)realloc(pntr,newsize);
void main()
char *c;
c = (char*)malloc(10);
c = " code ";
c = (char*) realloc(c,20);
c = " codeskulls ";
  1. free

    This is used to release the memory allocation at runtime.

syntax: free(pntr);