Challenge - 5 Problems
Malloc Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this malloc usage?
Consider the following C code snippet. What will be printed when it runs?
C
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = (int *)malloc(3 * sizeof(int)); if (ptr == NULL) { printf("Memory allocation failed\n"); return 1; } ptr[0] = 10; ptr[1] = 20; ptr[2] = 30; printf("%d %d %d\n", ptr[0], ptr[1], ptr[2]); free(ptr); return 0; }
Attempts:
2 left
💡 Hint
Remember that malloc allocates memory but does not initialize it. Here, values are assigned before printing.
✗ Incorrect
The code allocates memory for 3 integers, assigns values 10, 20, and 30 to them, then prints these values. Since the values are explicitly set, the output is '10 20 30'.
❓ Predict Output
intermediate2:00remaining
What error does this code raise?
What error will this C code produce when run?
C
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = malloc(-5 * sizeof(int)); if (ptr == NULL) { printf("Allocation failed\n"); return 1; } ptr[0] = 1; printf("%d\n", ptr[0]); free(ptr); return 0; }
Attempts:
2 left
💡 Hint
malloc expects a size_t argument, which is unsigned. Negative values convert to large positive numbers.
✗ Incorrect
The negative value is converted to a very large unsigned number, causing malloc to try to allocate a huge amount of memory. This usually fails or causes undefined behavior at runtime.
🔧 Debug
advanced2:00remaining
Why does this malloc code cause a memory leak?
Examine the code below. Why does it cause a memory leak?
C
#include <stdlib.h> int main() { int *ptr = malloc(10 * sizeof(int)); ptr = malloc(20 * sizeof(int)); free(ptr); return 0; }
Attempts:
2 left
💡 Hint
Think about what happens to the pointer after the first malloc before the second malloc.
✗ Incorrect
The pointer ptr is assigned memory twice without freeing the first allocation. The first allocated memory address is lost and never freed, causing a memory leak.
📝 Syntax
advanced2:00remaining
Which option causes a compilation error?
Which of the following malloc usages will cause a compilation error?
Attempts:
2 left
💡 Hint
Check the syntax of the sizeof operator in each option.
✗ Incorrect
Option B uses '5 * int' which is invalid syntax because 'int' is a type, not a value. sizeof requires a type or expression inside parentheses.
🚀 Application
expert2:00remaining
How many integers can be safely stored?
Given this code, how many integers can be safely stored in the allocated memory?
C
#include <stdlib.h> int main() { int *arr = malloc(50 * sizeof(*arr)); if (!arr) return 1; // How many integers can arr hold? free(arr); return 0; }
Attempts:
2 left
💡 Hint
malloc allocates memory for 50 times the size of one integer.
✗ Incorrect
The malloc call allocates memory for 50 integers because it multiplies 50 by the size of the type pointed to by arr, which is int.