Dynamic Memory Allocation : Unlock the secrets of dynamic memory allocation in C with this deep dive into malloc() vs calloc(). Whether you’re preparing for a coding interview or refining your C programming skills, this guide breaks down the top 5 key differences between these powerful functions. From initialization behavior to memory efficiency, discover when to use each — and boost your confidence in memory management. Master C like a pro, one byte at a time!
1. malloc() (Memory Allocation)
void* malloc(size_t size);
- Allocates uninitialized memory of
sizebytes. - Returns a pointer to the allocated memory.
- If allocation fails, returns
NULL. - The allocated memory contains garbage values (random data).
Example of malloc()
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int*) malloc(5 * sizeof(int)); // Allocates memory for 5 integers
if (ptr == NULL) {
printf(\"Memory allocation failed\\n\");
return 1;
}
for (int i = 0; i < 5; i++) {
ptr[i] = i + 1; // Assign values
printf(\"%d \", ptr[i]);
}
free(ptr); // Free allocated memory
return 0;
}
📌 Key Points:
✔ Allocates memory but does not initialize it.
✔ Faster than calloc() as it does not set values to zero.
2. calloc() (Contiguous Allocation)
void* calloc(size_t num, size_t size);
- Allocates memory for an array of
numelements, each ofsizebytes. - Initializes all allocated memory to zero.
- Returns a pointer to the allocated memory.
- If allocation fails, returns
NULL.
Example of calloc()
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int*) calloc(5, sizeof(int)); // Allocates memory for 5 integers and initializes them to zero
if (ptr == NULL) {
printf(\"Memory allocation failed\\n\");
return 1;
}
for (int i = 0; i < 5; i++) {
printf(\"%d \", ptr[i]); // All values will be 0
}
free(ptr); // Free allocated memory
return 0;
}
📌 Key Points:
✔ Allocates and initializes memory to zero.
✔ Slightly slower than malloc() due to initialization.
3. Differences Between malloc() and calloc() [Dynamic Memory Allocation]
| Feature | malloc() | calloc() |
|---|---|---|
| Initialization | Garbage values | Zeros |
| Speed | Faster | Slower (zero initialization) |
| Parameters | Single (size) | Two (num and size) |
| Use case | When initialization is not needed | When zero-initialization is required |
4. Common Mistakes & Best Practices
🔴 Forgetting to Free Memory
int *p = (int*) malloc(10 * sizeof(int));
// If free(p) is not called, it leads to a memory leak.
✅ Solution: Always free allocated memory.
free(p);
🔴 Dereferencing NULL Pointers
int *p = (int*) malloc(0); // Might return NULL or valid pointer
*p = 5; // Undefined behavior if p is NULL
✅ Solution: Always check if malloc() or calloc() returns NULL.
🔴 Incorrect Pointer Casting
// Not required in C but needed in C++
int *p = malloc(10 * sizeof(int)); // No need to cast in C
✅ Solution: Casting is required in C++ but optional in C.
🔴 Misusing sizeof()
int *p = (int*) malloc(10); // Wrong (only 10 bytes allocated)
✅ Solution: Use sizeof(int).
int *p = (int*) malloc(10 * sizeof(int)); // Correct
5. Important Interview Questions
1. What is the difference between malloc() and calloc()?
malloc(size_t size): Allocates uninitialized memory.calloc(size_t num, size_t size): Allocates memory and initializes it to zero.
2. Why is calloc() slower than malloc()?
calloc()initializes memory to zero, which adds extra processing overhead.
3. When should we use calloc() over malloc()?
- Use
calloc()when you want memory initialized to zero (e.g., arrays).
4. What happens if we allocate 0 bytes using malloc(0) or calloc(0, size)?
- Behavior is implementation-defined:
- Some implementations return
NULL. - Others return a valid pointer that cannot be dereferenced.
- Some implementations return
5. What happens if malloc() or calloc() fails?
- They return
NULL. Always check before using the pointer.
6. Can we use free() on memory allocated with calloc()?
- Yes. The memory allocated with
malloc()orcalloc()should be freed usingfree().
7. Is calloc(n, sizeof(int)) the same as malloc(n * sizeof(int)) followed by memset()?
- Almost, but not always:
calloc()guarantees zero-initialization.malloc()+memset()might not always be optimized ascalloc().
8. Can calloc() return more memory than requested?
- Yes, due to memory alignment and internal fragmentation.
9. How does calloc() ensure zero-initialization?
- It internally calls
memset()to set memory to zero.
10. What happens if we free a NULL pointer?
free(NULL)does nothing (safe to call).
11. What are alternatives to malloc() and calloc()?
realloc(): Resizes allocated memory.brk()andsbrk(): System-level memory allocation.mmap(): Used in large memory allocations.
12. How does malloc() internally work?
- Calls
sbrk()ormmap()to request memory from the OS.
13. How to avoid memory leaks with malloc() and calloc()?
- Always free memory with
free(). - Use tools like
valgrindto detect leaks.
💛 Support Embedded Prep
If you find our tutorials helpful and want to support our mission of sharing high-quality embedded system knowledge, you can contribute by buying us a coffee. Every small contribution helps us keep creating valuable content for learners like you. ☕
Thank you for your support — it truly keeps Embedded Prep growing. 💻✨
14. How does calloc() affect performance?
- It initializes memory, making it slightly slower.
15. Can we reallocate memory allocated using calloc()?
- Yes, use
realloc().
🛠 Best Practices:
✔ Always check if malloc() or calloc() returns NULL.
✔ Use free() to release memory.
✔ Prefer calloc() when zero-initialization is required.
You can also Visit other tutorials of Embedded Prep
- What is eMMC (Embedded MultiMediaCard) memory ?
- Top 30+ I2C Interview Questions
- Bit Manipulation Interview Questions
- Structure and Union in c
- Little Endian vs. Big Endian: A Complete Guide
- Merge sort algorithm
Special thanks to @embedded-prep for contributing to this article on Embedded Prep
Mr. Raj Kumar is a highly experienced Technical Content Engineer with 7 years of dedicated expertise in the intricate field of embedded systems. At Embedded Prep, Raj is at the forefront of creating and curating high-quality technical content designed to educate and empower aspiring and seasoned professionals in the embedded domain.
Throughout his career, Raj has honed a unique skill set that bridges the gap between deep technical understanding and effective communication. His work encompasses a wide range of educational materials, including in-depth tutorials, practical guides, course modules, and insightful articles focused on embedded hardware and software solutions. He possesses a strong grasp of embedded architectures, microcontrollers, real-time operating systems (RTOS), firmware development, and various communication protocols relevant to the embedded industry.
Raj is adept at collaborating closely with subject matter experts, engineers, and instructional designers to ensure the accuracy, completeness, and pedagogical effectiveness of the content. His meticulous attention to detail and commitment to clarity are instrumental in transforming complex embedded concepts into easily digestible and engaging learning experiences. At Embedded Prep, he plays a crucial role in building a robust knowledge base that helps learners master the complexities of embedded technologies.

I just like the valuable information you provide on your articles.I’ll bookmark your blog and test again here frequently. I’m quite certain I’ll be informed plenty of new stuff proper right here! http://www.kayswell.com Good luck for the next!
If some one needs to be updated with latest technologies therefore he must be go to see this web site and be up to date every day. http://www.kayswell.com
I’d like to thank you for the efforts you have put in writing this blog.I’m hoping to check out the same high-grade content from you later on as well. In truth, http://www.kayswell.com your creative writing abilities has motivated me to get my very own website now 😉
Hey I know this is off topic but I was wondering if you knew of any widgetsI could add to my blog that automatically tweet my newest twitter updates. http://www.kayswell.com
Hello to all, the contents existing at this web page are genuinely remarkable for people knowledge, well, keep up the good work fellows. http://www.kayswell.com
It’s a pity you don’t have a donate button! I’d definitely donate to this fantastic blog! I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to new updates and will share this blog with my Facebook group. Talk soon!
Great blog you’ve got here.. It’s difficult to find excellent writing like yours these days. I seriously appreciate individuals like you! Take care!!
constantly i used to read smaller articles or reviews that also clear their motive,and that is also happening with this piece of writing which I am reading here.
Hello mates, its wonderful post on the topic of cultureand entirely explained, keep it up all the time.