Memory allocation flow - Time & Space Complexity
When a program asks for memory, it takes some time to find and give that space.
We want to see how the time to get memory grows as the program asks for more.
Analyze the time complexity of the following code snippet.
#include <stdlib.h>
int main() {
int n = 1000;
for (int i = 0; i < n; i++) {
int* ptr = (int*)malloc(sizeof(int));
if (ptr == NULL) return -1;
// use ptr
free(ptr);
}
return 0;
}
This code requests memory for one integer n times, then frees it each time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling malloc and free inside a loop.
- How many times: Exactly n times, once per loop iteration.
Each time the loop runs, the program asks for memory once and frees it once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 (10 malloc + 10 free) |
| 100 | 200 (100 malloc + 100 free) |
| 1000 | 2000 (1000 malloc + 1000 free) |
Pattern observation: The number of operations grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to allocate and free memory grows linearly as the number of requests increases.
[X] Wrong: "Memory allocation is instant and does not affect performance."
[OK] Correct: Each malloc call takes time to find free space and manage memory, so many calls add up and slow the program.
Understanding how memory allocation time grows helps you write efficient programs and answer questions about resource use in real projects.
"What if we allocated memory once outside the loop and reused it inside? How would the time complexity change?"
Practice
malloc function do in C programming?Solution
Step 1: Understand the purpose of
mallocmallocis used to allocate memory dynamically on the heap during program execution.Step 2: Differentiate from other memory functions
freereleases memory, declaration creates variables, and copying data is done by functions likememcpy.Final Answer:
Allocates a block of memory on the heap -> Option BQuick Check:
malloc= Allocate memory [OK]
- Confusing malloc with free
- Thinking malloc declares variables
- Assuming malloc copies data
malloc?Solution
Step 1: Calculate total memory needed
To allocate memory for 10 integers, multiply 10 by the size of an int: 10 * sizeof(int).Step 2: Check pointer type and assignment
The pointer must be of typeint *and assigned the result ofmalloc. int *ptr = malloc(10 * sizeof(int)); matches this.Final Answer:
int *ptr = malloc(10 * sizeof(int)); -> Option DQuick Check:
Correct malloc size and pointer type = int *ptr = malloc(10 * sizeof(int)); [OK]
- Not multiplying by sizeof(int)
- Using wrong pointer type
- Allocating too little memory
int *ptr = malloc(4 * sizeof(int));
if (ptr == NULL) {
printf("Allocation failed\n");
} else {
ptr[0] = 10;
ptr[1] = 20;
printf("%d %d\n", ptr[0], ptr[1]);
free(ptr);
}Solution
Step 1: Check memory allocation and NULL condition
The code allocates memory for 4 integers. If allocation fails, it prints "Allocation failed". Otherwise, it proceeds.Step 2: Assign and print values
Since allocation likely succeeds, ptr[0] = 10 and ptr[1] = 20 are set, then printed as "10 20".Final Answer:
10 20 -> Option AQuick Check:
Successful malloc prints assigned values [OK]
- Ignoring NULL check
- Assuming uninitialized values print zero
- Forgetting to free memory
char *str = malloc(5); strcpy(str, "Hello World"); free(str);
Solution
Step 1: Check allocated memory size
Memory allocated is 5 bytes, but the string "Hello World" needs 12 bytes (11 chars + 1 null terminator).Step 2: Understand consequences of insufficient memory
Copying a larger string into smaller allocated space causes buffer overflow and undefined behavior.Final Answer:
Memory allocated is too small for the string -> Option AQuick Check:
Allocated size < string length = Memory allocated is too small for the string [OK]
- Ignoring string length vs allocated size
- Not checking malloc return value
- Assuming strcpy auto-expands memory
Solution
Step 1: Understand memory allocation and initialization
callocallocates and initializes memory to zero automatically, perfect for this task.Step 2: Check safe memory release
free(arr);correctly releases the allocated memory after use.Final Answer:
int *arr = calloc(5, sizeof(int)); free(arr); -> Option CQuick Check:
calloc zero-initializes and malloc does not [OK]
- Using malloc without initializing memory
- Allocating too little memory
- Not freeing dynamically allocated memory
Ready to prove it?
Pass the test and this pattern moves unknown
