Dynamic memory allocation allows programs to allocate memory at runtime, which is essential when the size of data structures is unknown beforehand.
1. malloc() (Memory Allocation)
void* malloc(size_t size);
- Allocates uninitialized memory of
size
bytes. - 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
num
elements, each ofsize
bytes. - 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()
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
valgrind
to detect leaks.
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.