Interview Kickstart has enabled over 3500 engineers to uplevel.
Dynamic memory allocation is a memory allocation process that allows us to allocate memory blocks based on the changing needs. For example, we can use dynamic memory allocation to create a program in which an array size can remain undecided until runtime. Dynamic memory allocation is implemented via four stdlib functions in the C language: malloc(), free(), calloc(), and realloc(). We’ll discuss each in detail in this article.
If you are preparing for a tech interview, check out our technical interview checklist, interview questions page, and salary negotiation e-book to get interview-ready! Also, read Python String join() Method, Sum Function in Python, and How to Read and Write Files in Python for more specific insights and guidance on Python concepts and coding interview preparation.
Having trained over 9,000 software engineers, we know what it takes to crack the toughest tech interviews. Since 2014, Interview Kickstart alums have been landing lucrative offers from FAANG and Tier-1 tech companies, with an average salary hike of 49%. The highest ever offer received by an IK alum is a whopping $933,000!
At IK, you get the unique opportunity to learn from expert instructors who are hiring managers and tech leads at Google, Facebook, Apple, and other top Silicon Valley tech companies.
Want to nail your next tech interview? Sign up for our FREE Webinar.
In this article, we’ll discuss:
The data memory in C/C++ is broadly divided into the following three spaces:
Before we move ahead, take a look at some of these fundamental differences between dynamic and static memory:
Note: Dynamic arrays are not a feature of the C programming language, but it provides other useful features, like calloc(), free(), etc., using which we can implement dynamic arrays.
Dynamic memory allocation is a concept that helps us allocate memory at runtime in C. It requires manual allocation and deallocation of memory as appropriate and is managed with the help of pointers to the newly allocated memory in a heap.
Dynamic memory allocation in C can be achieved using the following four functions in the stdlib.h header file: malloc(), calloc(), free(), and realloc().
Here are some of the key differences between malloc, calloc, free, and realloc in C:
The malloc() function is a C library function that dynamically allocates a single block of requested memory in the heap memory area at runtime. It takes just one parameter — the size of memory requested in bytes. The malloc() function returns a pointer of type void to the allocated memory after successful allocation, which can be type-casted into a pointer of any type.
Also, it returns NULL if the memory is insufficient for allocation. As a tutorial or an example of dynamic memory allocation using malloc in C, if you write the statement malloc(10), it will dynamically allocate 10 bytes of memory. Note that malloc doesn’t initialize the memory during execution, so it initially stores garbage values.
Here, requiredSizeBytes represents the total size of the memory block required in bytes.
void *malloc(size_t requiredSizeBytes)
The following example allocates 200 bytes of memory, since float takes 4 bytes of memory, and we want to store 50 float type numbers.
pointerToMemoryBlock = (float*) malloc(50 * sizeof(float));
Like malloc, calloc is also defined in the header stdlib.h and allocates memory at runtime in the heap memory area. Unlike malloc, calloc allocates multiple contiguous blocks of requested memory and initializes all bytes to zero.
It takes two arguments: the number of elements and the size of each element in bytes. It returns a void pointer to the memory after successful allocation and returns NULL if memory is insufficient for allocation.
Here, numberOfBlocks represents the total number of memory blocks requested for allocation, and sizeOfEachBlock represents the size of each block to be allocated.
void *calloc(size_t numberOfBlocks, size_t sizeOfEachBlock);
In this example, since float is 4 bytes, 10 blocks of 4 bytes each are allocated.
pointerToMemoryBlocks = (float*) calloc(10, sizeof(float));
Dynamically allocated memory does not get released automatically, so the question is, how will you free the allocated memory in C? For this, we need a function to deallocate the memory that was dynamically allocated by malloc or calloc. The free() function in the standard C library serves the purpose of releasing the memory of deallocating the memory held by malloc or calloc once the work is done.
If free() is not called, the memory is held till the program terminates. It is recommended to release the dynamically allocated memory after the program terminates, so there is no memory leak and the previously held memory is available for future use.
Here, pointerToMemory represents the pointer to the memory block that needs to be released or deallocated.
void free(void *pointerToMemory);
In the statement below, the memory block/blocks allocated via malloc() or calloc() that pointerToMemoryBlock points to is released using free().
Suppose we’ve allocated more or less memory than required. In that case, we can change the size of the previously allocated memory space using realloc().
The realloc() function in C is used to resize the memory block allocated through malloc() and calloc() library function without losing any old data. Failure of this function call will result in the return value NULL.
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size. The realloc() method returns a void pointer to the reallocated and likely moved memory block. If the size of the new memory block is set to zero, then the block memory is freed, the return value is NULL, and the pointer is left pointing at a freed block.
Here, pointerToMemory represents the pointer to the memory block that malloc() or calloc() allocated, and newBlockSize represents the new size of the memory block being reallocated.
void *realloc(void *pointerToMemory, size_t newBlockSize);
In this example, realloc allocates memory of updated size newMemoryBlockSize to the pointer pointerToMemoryBlock , which points to the memory block whose size needs to be updated.
pointerToMemoryBlock = realloc(pointerToMemoryBlock, newMemoryBlockSize);
1. What is the problem of using dynamic memory allocation?
The problem is that dynamically allocated memory isn’t automatically deallocated. It needs to be explicitly released. Suppose the developer misses or forgets to explicitly deallocate, and the memory isn’t released each time it is dynamically allocated. In that case, there can be a memory leak that reduces your machine’s performance.
2. How can dynamic memory allocation be achieved in C?
Dynamic memory allocation in C is achieved using a heap along with four stdlib functions: malloc, calloc, free, and realloc. Here, malloc and free are the two main dynamic memory functions.
3. Can I increase the size of dynamically allocated memory? What about statically allocated memory?
As the word “static” suggests, you cannot change the size of a statically allocated memory. But with dynamically allocated memory, you can change the size using realloc, which can be faster than calling free and malloc one after the other. Also, this ensures that the new reallocated memory block contains the contents in the original memory block.
4. What happens if we don't deallocate dynamic memory in our program that continuously allocates it?
If a code is executed frequently enough and dynamic memory has not been deallocated properly, there will be growing memory leaks, which is understandably discouraged. That said, a program that keeps most allocated memory until the program exits and doesn’t have deallocation steps in between usually is faster in terms of performance.
5. What is the difference in execution speed when using dynamic memory allocation vs. when using static memory allocation?
Dynamic memory allocation is slower than static memory allocation as dynamic memory has to be allocated during execution, which reduces execution speed.
6. What is the difference between static and dynamic allocation?
Static memory allocation occurs before the program executes and the variables are permanently allocated. Dynamic memory allocation occurs during execution, memory allocated can be altered, and the variables are allocated only if their program unit is active.
Whether you’re a Coding Engineer gunning for Software Developer or Software Engineer roles, a Tech Lead, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!
If you’re looking for guidance and help with getting started, sign up for our FREE webinar. As pioneers in the field of technical interview preparation, we have trained thousands of software engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!
Attend our webinar on
"How to nail your next tech interview" and learn