Dynamic Memory Allocation in C

I assume that you have basic knowledge about pointers and computer memory.

Photo by Liam Briese on Unsplash

According to Wikipedia,

Memory management is a form of resources management applied to computer memory. The essential requirement of memory management is to provide ways to dynamically allocate portions of memory to programs at their request, and free it for reuse when no longer needed. This is critical to any advanced computer system where more than a single process might be underway at any time.

There are two places where data gets stored.

  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.

Learn more about Stack and Heap

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.

Let’s talk about Arrays. Arrays can be used for data storage but they are always of fixed size. The coder must know the size of the array or an elements while writing programs. In C, a variable cannot be used to specify the size of the array. In most situations, it is not possible for coder to know the size of the required memory until execution time or run time. For example, let us consider a program which asks user for numbers of employees. According to given number of employees, it asks salary of each employee and store it in an array. Suppose the size of an array is fixed to 500. The program would not work if the number of employees is more than 500(>500). If the number of employees is 150 , only 150 memory locations are used and rest 350 memory locations which are reserved are not used. Here, 350 memory locations are wasted. In this situation, Dynamic Memory Allocation will be useful to reduce memory wastage.

I will assume that you know about pointer to an array. While initializing conventional array, your computer reserves fixed memory size at the beginning of the program which is obviously ineffective but this does not occur if we use array to pointer concept. The use of a pointer variable to represent an array requires some type of initial memory assignment before the array elements are processed. This is known as Dynamic Memory Allocation(DMA). At runtime, a program can request more memory as per it’s need and frees if not required using Dynamic Memory Allocation. Dynamic Memory Allocation is all about allocating and freeing memory at run time or execution time.

We can use malloc(), calloc(), alloc(), and realloc() which are library functions defined within <stdlib.h>

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));

The above code allocates space in memory for 150 elements of int type.

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));

The above code allocates contiguous space in memory for 150 elements of float type.

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);

The above code reallocates space in memory for 300 elements of int type.

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);

The above code free the memory allocated by malloc().

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);

}

Note: This is my first article on the Internet. I would greatly appreciate your feedback. Thank you for reading until the end. Happy Memory Allocating ;)

Hola! They call me Hacker

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