Challenge - 5 Problems
Memory Leak Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of code with missing free() call
What is the output of this C program snippet?
C
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = malloc(sizeof(int)); *ptr = 10; printf("%d\n", *ptr); // missing free(ptr); return 0; }
Attempts:
2 left
💡 Hint
Think about what happens if you allocate memory but don't free it.
✗ Incorrect
The program prints 10 because the allocated memory holds the value 10. Missing free() causes a memory leak but does not affect output here.
🧠 Conceptual
intermediate2:00remaining
Cause of memory leak in this code
Which line in the following code causes a memory leak?
C
#include <stdlib.h> void func() { int *p = malloc(4 * sizeof(int)); p = malloc(10 * sizeof(int)); free(p); }
Attempts:
2 left
💡 Hint
Think about what happens to the first allocated memory.
✗ Incorrect
The second malloc overwrites pointer p without freeing the first allocated memory, causing a memory leak.
🔧 Debug
advanced2:00remaining
Identify the memory leak in this function
What is the memory leak issue in this function?
C
#include <stdlib.h> #include <string.h> char* create_string() { char *str = malloc(20); if (!str) return NULL; str = "Hello"; return str; }
Attempts:
2 left
💡 Hint
Look at what happens to the pointer after malloc.
✗ Incorrect
The pointer str is assigned a string literal after malloc, losing the reference to allocated memory, causing a leak.
📝 Syntax
advanced2:00remaining
Which option causes a compile-time error?
Which of the following code snippets will cause a compile-time error?
Attempts:
2 left
💡 Hint
Consider if the pointer is initialized before free.
✗ Incorrect
Freeing an uninitialized pointer (C) causes undefined behavior and may cause compile or runtime errors depending on compiler and environment.
🚀 Application
expert3:00remaining
How many memory leaks occur in this program?
How many memory leaks occur when this program runs?
C
#include <stdlib.h> int main() { int *a = malloc(10 * sizeof(int)); int *b = malloc(5 * sizeof(int)); a = b; free(b); return 0; }
Attempts:
2 left
💡 Hint
Check which allocated memory is lost without free.
✗ Incorrect
The original memory allocated to 'a' is lost when 'a' is assigned 'b' without freeing first, causing one memory leak.