Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Dynamic Memory Allocation in C Using malloc(), calloc(), free(), and realloc()

Last updated by Utkarsh Sahu on Sep 25, 2024 at 10:59 PM | Reading time: 10 minutes

The fast well prepared banner

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

Dynamic Memory Allocation in C Using malloc(), calloc(), free(), and realloc()
Hosted By
Ryan Valles
Founder, Interview Kickstart
strategy
Our tried & tested strategy for cracking interviews
prepare list
How FAANG hiring process works
hiring process
The 4 areas you must prepare for
hiring managers
How you can accelerate your learnings

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:

  • Memory Spaces in C and C++
  • Dynamic Memory vs. Static Memory
  • Dynamic Memory Allocation in C
  • Difference Between malloc(), calloc(), free(), and realloc()
  • The malloc() Function in C
  • The calloc() Function in C
  • The free() Function in C
  • The realloc() Function in C
  • FAQs on Dynamic Memory Allocation in C

Memory Spaces in C and C++

The data memory in C/C++ is broadly divided into the following three spaces:

1. Static Memory:

  • Static memory is usually located at the starting of the RAM area.
  • The variables defined outside functions are located in static memory. The static keyword is not about where such variables are stored but about specifying the scope as local to the current module. 
  • Even if a variable is defined inside a function, if it is declared static explicitly, then it is also stored in static memory.
  • The main address allocation to variables is done when the compiler and the linker work together in the form of a software development toolkit.
  • Usually, all the remaining RAM that is not part of static memory storage makes up the dynamic storage area. The dynamic storage area contains the remaining two memory spaces: automatic variables and dynamic memory.

2. Automatic Variables:

  • If a variable is defined inside a function and isn’t explicitly declared as static, it is automatic. We can also use the keyword auto to declare a variable as automatic, but it’s rarely needed.
  • Automatic variables are stored in a stack. This stack is located with the help of a linker and is usually positioned at the end of the dynamic storage area.
  • If the keyword register is used, or if there have been some compiler optimizations, variables may be stored in registers for some part of their lifetimes or all of it.
  • With the automatic variables stored in a stack at the end of the dynamic storage area, the rest of the area is usually allocated as a heap used for dynamic memory allocation.

3. Dynamic Memory:

  • Dynamic memory allocation occurs via a heap and with the help of four stdlib functions: malloc, free, calloc, and realloc.
  • Unlike static memory, in dynamic memory, the size allocated can be changed later, which helps in optimizing memory usage based on data size.
  • Dynamic memory is most helpful when the memory size needed is unknown to you, so you can dynamically allocate it as appropriate.

Dynamic Memory vs. Static Memory

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 in C

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().

Differences Between malloc(), calloc(), free(), and realloc()

Here are some of the key differences between malloc, calloc, free, and realloc in C:

The malloc() Function 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.

Syntax

Here, requiredSizeBytes represents the total size of the memory block required in bytes.

void *malloc(size_t requiredSizeBytes)

Example

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

The calloc() Function in C

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.

Syntax

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

Example

In this example, since float is 4 bytes, 10 blocks of 4 bytes each are allocated.

pointerToMemoryBlocks = (float*) calloc(10, sizeof(float));

The free() Function in C

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.

Syntax

Here, pointerToMemory represents the pointer to the memory block that needs to be released or deallocated.

void free(void *pointerToMemory);

Example

In the statement below, the memory block/blocks allocated via malloc() or calloc() that pointerToMemoryBlock points to is released using free().

free(pointerToMemory);

The realloc() Function in C

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.

Syntax

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

Example

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

FAQs on Dynamic Memory Allocation in C 

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.

Ready to Nail Your Next Coding Interview?

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!

Sign up now!

Last updated on: 
November 20, 2024
Author

Utkarsh Sahu

Director, Category Management @ Interview Kickstart || IIM Bangalore || NITW.

Attend our Free Webinar on How to Nail Your Next Technical Interview

Register for our webinar

How to Nail your next Technical Interview

1
Enter details
2
Select webinar slot
First Name Required*
Last Name Required*
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.

Dynamic Memory Allocation in C Using malloc(), calloc(), free(), and realloc()

Worried About Failing Tech Interviews?

Attend our webinar on
"How to nail your next tech interview" and learn

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Our tried & tested strategy for cracking interviews
blue tick
How FAANG hiring process works
blue tick
The 4 areas you must prepare for
blue tick
How you can accelerate your learnings
Register for Webinar
entroll-image