Dynamic memory allocation

In C programming language, memory is allocated in two ways:

  • Static memory allocation or compile time memory allocation
  • Dynamic memory allocation or run time allocation

Static Memory Allocation:

The static memory allocation is also known as compile-time and in this memory is allocated at compile time that is before the program execution.

The program must determine the memory needed for any type of variable before running the program. Once the memory is allocated it cannot be re-sized.


int arr[5] = {1, 2, 3, 4, 5};

In the above example the size of the array is 5 and if it needs to be changed it has to be done manually and if we try to store more values than the size the compiler complains.

Dynamic memory allocation:

It is practically impossible for large-scale programs to determine the memory needed before running a program and allocating a huge amount of memory would lead to waste of memory if only less memory is actualy required.

Hence the solution needed is to allocate the memory dynamically at run time which is used to allocate and deallocate memory of different sizes during runtime when the memory is actually needed and its size is known.

In general, one large memory region exists that is used to fulfill the different memory requests. This region is often called.

The task of the memory management functions is to serve the memory requests by allocating a part of the heap and provide it to the requester. The same applies if the user frees an previously allocated memory region, thus giving it back to the heap.

At any time, the memory management functions must keep track of the used and unused memory regions of the heap. Some parts of the heap are in use (thus allocated by the user), while other parts are free, ready to be allocated.

C programming language provides a few library functions defined in the header file “stdlib.h” to allocate the memory dynamically. These library functions are known as memory management functions.

The library functions are as follows:

mallocallocates the requested size of the bytes and returns a void pointer pointing to the first bytes of the allocated space
callocallocates space for an array of elements, initialize to zero and return void pointers to the first bytes of allocated space
reallocModify the size of the existing allocated space
freeRelease the previously alloacted space

Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: