malloc function - Time & Space Complexity
When we use malloc in C, it asks the system for memory space. Understanding how long this takes helps us write faster programs.
We want to know how the time to get memory changes as the requested size grows.
Analyze the time complexity of the following code snippet.
#include <stdlib.h>
int main() {
int n = 1000;
int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
return 1; // allocation failed
}
// use arr ...
free(arr);
return 0;
}
This code asks the system to reserve space for 1000 integers using malloc.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
mallocfunction internally searches for a free memory block large enough to fit the requested size. - How many times: This search happens once per call, but may involve checking multiple memory blocks depending on the allocator's state.
As the requested size grows, malloc may need to look through more memory blocks to find a fit.
| Input Size (bytes) | Approx. Operations |
|---|---|
| 100 | Few checks, fast allocation |
| 1,000 | More checks, takes longer |
| 10,000 | Even more checks, slower |
Pattern observation: The time to allocate grows roughly with how many free blocks the system must check, which can increase with requested size.
Time Complexity: O(n)
This means the time to allocate memory grows linearly with the size requested or the number of free blocks checked.
[X] Wrong: "malloc always runs instantly no matter the size."
[OK] Correct: Actually, malloc may take longer for bigger requests because it searches for a suitable free space, so time can grow with size.
Understanding how memory allocation time grows helps you write efficient programs and shows you know how system resources work behind the scenes.
"What if we used a custom memory pool instead of malloc? How would the time complexity change?"
Practice
malloc function do in C programming?Solution
Step 1: Understand the purpose of malloc
Themallocfunction is used to allocate memory dynamically while the program is running, not at compile time.Step 2: Differentiate malloc from other functions
Unlikefreewhich releases memory, orprintfwhich outputs text,malloconly allocates memory.Final Answer:
Allocates a block of memory dynamically during program execution -> Option CQuick Check:
malloc = allocate memory [OK]
- Confusing malloc with free
- Thinking malloc prints output
- Assuming malloc declares variables
malloc?Solution
Step 1: Calculate correct size for allocation
To allocate memory for 10 integers, multiply 10 by the size of an integer usingsizeof(int).Step 2: Use correct pointer type and syntax
The pointer must be declared asint *and assigned the result ofmalloc. int *ptr = malloc(10 * sizeof(int)); correctly does this.Final Answer:
int *ptr = malloc(10 * sizeof(int)); -> Option AQuick Check:
malloc size = count * sizeof(type) [OK]
- Not multiplying by sizeof(int)
- Using wrong pointer type
- Allocating too little memory
int *p = malloc(4 * sizeof(int));
if (p == NULL) {
printf("Allocation failed\n");
} else {
p[0] = 10;
p[1] = 20;
printf("%d %d\n", p[0], p[1]);
}
free(p);Solution
Step 1: Check if malloc succeeded
The code checks ifpis NULL. If not NULL, allocation succeeded and memory can be used.Step 2: Assign and print values
Values 10 and 20 are assigned top[0]andp[1]. Then they are printed, so output is "10 20".Final Answer:
10 20 -> Option DQuick Check:
malloc success prints assigned values [OK]
- Ignoring NULL check
- Printing uninitialized memory
- Forgetting to free memory
char *str = malloc(5);
strcpy(str, "Hello World");
printf("%s", str);
free(str);Solution
Step 1: Check allocated memory size
The string "Hello World" needs 12 bytes (11 chars + 1 for '\0'), but only 5 bytes are allocated.Step 2: Understand consequences of small allocation
Copying a larger string into smaller allocated memory causes buffer overflow and undefined behavior.Final Answer:
malloc size is too small for the string -> Option BQuick Check:
Allocate enough memory for string + '\0' [OK]
- Allocating less memory than string length
- Calling free before using memory
- Wrong printf format for strings
malloc and realloc to achieve this?Solution
Step 1: Allocate initial memory with malloc
Start by allocating memory for the initial array size usingmalloc.Step 2: Use realloc to resize when array is full
When the array is full, usereallocto double the memory size safely without losing data.Step 3: Avoid incorrect usage
Using malloc repeatedly without freeing old memory causes leaks, allocating maximum size upfront wastes memory, and using realloc before malloc is incorrect.Final Answer:
Start with malloc for initial size, then use realloc to double size when needed -> Option AQuick Check:
malloc first, then realloc to grow [OK]
- Calling realloc before malloc
- Allocating max size upfront wasting memory
- Not freeing old memory causing leaks
Ready to prove it?
Pass the test and this pattern moves unknown
