Dynamic Memory Allocation in C

Photo by Liam Briese on Unsplash
  1. Stack: A stack is a area of computer’s memory which stores variables created by a function. In stack, variables are declared, stored and initialized during runtime and destroyed after program execution.
  2. Heap: The heap is used by programming languages to store global variables. It supports Dynamic memory allocation. Heap does not destroy data itself.

Dynamic Memory Allocation(DMA)

The process of allocating or freeing memory at run time or execution time is known as Dynamic Memory Allocation. This reserves the memory in heap required by the program at program runtime and returns the reserved memory to the system once the use of reserved memory is completed.

Memory allocation: malloc()

malloc()is used to allocate block of memory at runtime. Malloc reserves a block of memory of the given size and it returns a pointer of type Void. We can typecast it to any type of pointer. It will return NULL pointer if it fails to allocate memory.

Syntax

void* malloc(byte-size)

Example

int *x;
x = (int*)malloc(150 * sizeof(int));

Contiguous allocation: calloc()

The calloc()is similar to malloc(). The calloc()allocates memory and initializes every bits to 0. calloc() accepts two arguments inestead of one.

Syntax

void *calloc(items, size);

Example

int *x;
x = (float*) calloc(150, sizeof(float));

Re-allocation: realloc()

If the allocated memory is insufficient or more than required, realloc()can be used to change the size of previously allocated memory.

Syntax

void* realloc(pointer, new-size)

Example

int *x;
x = (int*)malloc(150 * sizeof(int));
x = (int*)realloc(x,300);

Free allocation: free()

Dynamically allocated memory created with calloc() or malloc() doesn't get freed on their own. You must use free() to free the memory.

Syntax

free(ptr);

Example

int *x;
x = (int*)malloc(150 * sizeof(int));
free(x);

Dynamic Memory Allocation Example

#include <stdio.h>
#include <stdlib.h>

void main()
{
int i, n;
int *x;

printf("Enter total number of elements: ");
scanf("%d", &n);

x = (int*) calloc(n,sizeof(int));

if(x == NULL)
{
printf("Not enough space.");
}

for(i = 0; i < n; i++)
{
scanf("%d", x+i);
}
for(i = 1; i < n; i++)
{
if(*x < *(x+i))
{
*x = *(x+i);
}
}

printf("Greatest number is %d", *x);
free(x);

}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store