C Notes
Top memory management interview questions for C programming covering malloc, calloc, free, memory leaks, segmentation faults, stack vs heap, and dynamic allocation.
Memory management is the cornerstone of C programming and the area where most bugs and interview questions originate. Unlike managed languages with garbage collection, C requires you to manually allocate and free memory. This guide covers the most important memory management questions asked in technical interviews.
Core Concepts
Q1: What are the four memory allocation functions in C?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// malloc: allocates uninitialized memory
int *p1 = (int*)malloc(5 * sizeof(int));
// calloc: allocates zero-initialized memory
int *p2 = (int*)calloc(5, sizeof(int));
// realloc: resizes previously allocated memory
p1 = (int*)realloc(p1, 10 * sizeof(int));
// free: releases allocated memory
free(p1);
free(p2);
return 0;
}| Function | Syntax | Initializes | Use Case |
|---|---|---|---|
| malloc | malloc(bytes) | No (garbage) | General allocation |
| calloc | calloc(count, size) | Yes (zeros) | Arrays, zero-init needed |
| realloc | realloc(ptr, new_size) | Preserves old data | Growing/shrinking buffers |
| free | free(ptr) | N/A | Release memory |
Q2: What happens if malloc fails?
#include <stdio.h>
#include <stdlib.h>
int main() {
// malloc returns NULL on failure
int *ptr = (int*)malloc(sizeof(int) * 1000000000L);
if (ptr == NULL) {
fprintf(stderr, "Memory allocation failed!\n");
return 1; // Handle gracefully
}
// Use ptr safely...
free(ptr);
return 0;
}Answer: malloc returns NULL when it cannot allocate the requested memory. Always check the return value before using the pointer.
Q3: What is a memory leak? How to detect it?
#include <stdlib.h>
void memory_leak_example() {
int *p = (int*)malloc(100 * sizeof(int));
// Function returns without free(p) - MEMORY LEAK!
// The allocated memory is inaccessible but not freed
}
void no_leak_example() {
int *p = (int*)malloc(100 * sizeof(int));
if (p == NULL) return;
// ... use p ...
free(p); // Properly freed
}
// Overwriting pointer without freeing - another common leak
void overwrite_leak() {
int *p = (int*)malloc(sizeof(int));
*p = 10;
p = (int*)malloc(sizeof(int)); // First allocation lost!
*p = 20;
free(p); // Only second allocation freed
}Detection methods:
- Valgrind:
valgrind --leak-check=full ./program - AddressSanitizer: compile with
-fsanitize=address - Custom allocation tracking with wrappers
Q4: What is a double-free bug?
#include <stdlib.h>
int main() {
int *p = (int*)malloc(sizeof(int));
*p = 42;
free(p);
// free(p); // DOUBLE FREE - Undefined Behavior!
// Prevention: set to NULL after free
p = NULL;
free(p); // safe - free(NULL) is a no-op
return 0;
}Answer: Freeing the same memory twice causes undefined behavior – heap corruption, crashes, or security vulnerabilities. Always set pointers to NULL after freeing.
Q5: What is use-after-free?
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p = (int*)malloc(sizeof(int));
*p = 42;
printf("Before free: %d\n", *p);
free(p);
// DANGEROUS: p still holds the old address
// printf("After free: %d\n", *p); // USE-AFTER-FREE! UB!
// Prevention:
p = NULL;
// Now any access through p will clearly crash (NULL deref)
return 0;
}Q6: Difference between stack and heap allocation?
Q7: What does realloc do in different scenarios?
p[0]=1, p[1]=2
Important: Always assign realloc's return to a temporary variable. If realloc fails, it returns NULL but doesn't free the original memory.
Q8: What is buffer overflow and how to prevent it?
Q9: How does free() know how many bytes to release?
Answer: The memory allocator stores metadata (usually just before the returned pointer) that records the size of the allocation. When you call free(ptr), it looks at this hidden header to determine how much memory to release. This is why:
- You must pass the exact pointer returned by malloc (not an offset)
- Passing a non-malloc'd pointer to free is undefined behavior
- Buffer overflows can corrupt this metadata, causing heap corruption
Q10: What is fragmentation?
#include <stdio.h>
#include <stdlib.h>
int main() {
// Allocate and free in a pattern that causes fragmentation
void *p1 = malloc(100);
void *p2 = malloc(200);
void *p3 = malloc(100);
void *p4 = malloc(200);
void *p5 = malloc(100);
// Free every other block
free(p1); // 100 bytes free
free(p3); // 100 bytes free
free(p5); // 100 bytes free
// Now 300 bytes total are free, but:
// Can we allocate 250 bytes? Maybe NOT!
// The free blocks are 100 bytes each, non-contiguous
void *big = malloc(250);
printf("Large allocation: %s\n", big ? "Success" : "Failed");
free(p2);
free(p4);
if (big) free(big);
return 0;
}Answer: Fragmentation occurs when free memory is broken into small, non-contiguous blocks. Even if total free memory is sufficient, a large allocation might fail because no single contiguous block is big enough.
Q11: What is the memory layout of a dynamically allocated 2D array?
arr3[1][2] = 6
Q12: What happens when you free memory that wasn't allocated by malloc?
#include <stdlib.h>
int main() {
int x = 10;
int *p = &x;
// free(p); // UNDEFINED BEHAVIOR! x is on stack, not heap
int *arr = (int*)malloc(10 * sizeof(int));
// free(arr + 5); // UNDEFINED BEHAVIOR! Not the original pointer
free(arr); // Correct: pass the original pointer
return 0;
}Q13: Implement a safe memory allocation wrapper
data[0] = 42
Common Memory Bugs Summary
| Bug | Cause | Prevention |
|---|---|---|
| Memory Leak | Forgetting to free | Always pair malloc/free, use tools |
| Double Free | Freeing twice | Set ptr to NULL after free |
| Use-After-Free | Accessing freed memory | NULL after free, scope discipline |
| Buffer Overflow | Writing past allocation | Bounds checking, safe functions |
| Dangling Pointer | Pointer to freed/invalid memory | NULL after free, careful lifetimes |
| Uninitialized Read | Reading malloc'd memory | Use calloc, or initialize immediately |
Interview Questions Summary
Q14: Can you allocate memory for a flexible array member? Yes – struct S { int count; int data[]; }; then malloc(sizeof(struct S) + n * sizeof(int)).
Q15: What is memory alignment? The requirement that data types be stored at addresses that are multiples of their size. Misaligned access can be slow or crash on some architectures.
Q16: What is alloca()? Allocates memory on the stack (freed automatically when function returns). Non-standard, dangerous for large allocations (stack overflow), but very fast.
Summary
Memory management in C requires understanding allocation mechanisms, ownership rules, and common pitfalls. Always check malloc returns, free exactly once, never access freed memory, and use tools like Valgrind and ASan during development. The interviewer wants to see that you understand not just the API, but the consequences of getting it wrong – security vulnerabilities, crashes, and data corruption.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Memory Management Interview Questions in C with Answers.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this C Programming topic.
Search Terms
c-programming, c programming, programming, interview, preparation, memory, management, questions
Related C Programming Topics