Challenge - 5 Problems
Memory Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of malloc and free usage
What is the output of this C program that allocates and frees memory?
C
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = (int *)malloc(sizeof(int)); if (ptr == NULL) { printf("Allocation failed\n"); return 1; } *ptr = 42; printf("Value: %d\n", *ptr); free(ptr); return 0; }
Attempts:
2 left
💡 Hint
Remember malloc returns a pointer to allocated memory which you can use before freeing it.
✗ Incorrect
The program allocates memory for an int, assigns 42, prints it, then frees the memory. So output is 'Value: 42'.
🧠 Conceptual
intermediate1:30remaining
Understanding realloc behavior
What happens when you call realloc with a NULL pointer in C?
Attempts:
2 left
💡 Hint
Think about realloc's behavior when given a NULL pointer.
✗ Incorrect
When realloc is called with NULL, it acts like malloc and allocates new memory of the given size.
🔧 Debug
advanced2:30remaining
Identify the cause of memory leak
What causes the memory leak in this code snippet?
C
#include <stdlib.h> void func() { int *arr = malloc(10 * sizeof(int)); arr = malloc(20 * sizeof(int)); free(arr); }
Attempts:
2 left
💡 Hint
Look at what happens to the pointer after the first malloc.
✗ Incorrect
The pointer 'arr' is assigned new memory without freeing the old one, so the first allocated memory is lost and leaked.
📝 Syntax
advanced1:30remaining
Identify the syntax error in memory allocation
Which option contains a syntax error in memory allocation?
C
int *ptr = malloc(sizeof(int) * 5);
Attempts:
2 left
💡 Hint
Check for missing semicolons or extra characters.
✗ Incorrect
Option D is missing a semicolon at the end, causing a syntax error.
🚀 Application
expert3:00remaining
Predict the number of allocated blocks
After running this code, how many distinct memory blocks are allocated and not freed?
C
#include <stdlib.h> int main() { int *a = malloc(10 * sizeof(int)); int *b = malloc(5 * sizeof(int)); free(a); a = malloc(20 * sizeof(int)); int *c = realloc(b, 15 * sizeof(int)); return 0; }
Attempts:
2 left
💡 Hint
Count allocations minus frees carefully, consider realloc behavior.
✗ Incorrect
Initially two blocks allocated (a and b). a is freed then reallocated (still 2 blocks). realloc on b resizes it, not new block. So 2 blocks remain allocated.