Challenge - 5 Problems
Master of calloc
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this calloc usage?
Consider the following C code snippet using calloc. What will be printed?
C
#include <stdio.h> #include <stdlib.h> int main() { int *arr = (int *)calloc(5, sizeof(int)); if (!arr) return 1; for (int i = 0; i < 5; i++) { printf("%d ", arr[i]); } free(arr); return 0; }
Attempts:
2 left
💡 Hint
calloc initializes allocated memory to zero.
✗ Incorrect
calloc allocates memory and sets all bytes to zero, so all integers in the array are zero.
❓ Predict Output
intermediate2:00remaining
What happens if calloc is called with zero elements?
What will be the output or behavior of this code?
C
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = (int *)calloc(0, sizeof(int)); if (ptr == NULL) { printf("NULL pointer\n"); } else { printf("Non-NULL pointer\n"); } free(ptr); return 0; }
Attempts:
2 left
💡 Hint
calloc with zero elements may return a unique pointer that should not be dereferenced.
✗ Incorrect
calloc(0, size) may return a non-NULL pointer that should not be dereferenced but can be freed safely.
🔧 Debug
advanced2:00remaining
Why does this calloc usage cause a runtime error?
Examine the code below. It compiles but crashes at runtime. What is the cause?
C
#include <stdio.h> #include <stdlib.h> int main() { int *arr = calloc(5, sizeof(int)); for (int i = 0; i <= 5; i++) { arr[i] = i * 2; } for (int i = 0; i < 5; i++) { printf("%d ", arr[i]); } free(arr); return 0; }
Attempts:
2 left
💡 Hint
Check the loop boundary conditions carefully.
✗ Incorrect
The loop uses i <= 5 which accesses arr[5], but valid indices are 0 to 4, causing out-of-bounds write.
🧠 Conceptual
advanced2:00remaining
What is the main difference between malloc and calloc?
Choose the correct statement about calloc compared to malloc.
Attempts:
2 left
💡 Hint
Think about what happens to the memory content after allocation.
✗ Incorrect
calloc sets all allocated bytes to zero, while malloc leaves memory uninitialized (contains garbage).
❓ Predict Output
expert2:00remaining
What is the output of this calloc and pointer arithmetic code?
Analyze the code and select the correct output.
C
#include <stdio.h> #include <stdlib.h> int main() { int *p = calloc(3, sizeof(int)); if (!p) return 1; *(p + 1) = 10; p++; printf("%d\n", *p); free(p - 1); return 0; }
Attempts:
2 left
💡 Hint
Remember how pointer arithmetic and calloc initialization work.
✗ Incorrect
calloc initializes all to zero, then *(p+1) = 10 sets second element. p++ moves pointer to second element, so *p is 10. free(p-1) frees original pointer.