- Executors
-
Learn
Learn Python Runnable examples, NumPy, pandas, and more Learn AI / Machine LearningNeural networks, ML and LLMs from scratch Learn C & C++ Pointers, memory, STL, and modern C++ Learn C#C# basics, OOP, LINQ, async, and .NET exercises Learn MatplotlibLine, bar, scatter and pie charts with live visualizers Learn RustOwnership, traits, error handling, and threads Learn GoSlices, interfaces, goroutines, and channels Python Algorithms Search, sorting, recursion, and visualizers O(n) C & C++ Algorithms Compare algorithms implemented in C and C++ Coding for Kids Learn to code by playing!
- QuizzesNew
- ChallengesNew
- For TeachersNew
- Updates
- Buy me a coffee
C malloc, calloc & free Quiz
This C quiz checks how you use malloc(), calloc(), realloc() and free() to work with memory on the heap. You will predict what small programs print and pick the safe way to allocate, grow and release a block.
Sample question
Question 1 of 10What does this print?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a = malloc(5 * sizeof *a);
if (a == NULL) return 1;
for (int i = 0; i < 5; i++) a[i] = i * i;
int sum = 0;
for (int i = 0; i < 5; i++) sum += a[i];
printf("%d\n", sum);
free(a);
return 0;
}
Show the answer
B. 30 The block holds the squares 0, 1, 4, 9 and 16, which add up to 30. sizeof *a is the size of one int, so 5 * sizeof *a is room for exactly five of them.
What this quiz covers
- Allocating arrays with
malloc(n * sizeof *p) calloc()vsmalloc(): zeroed memory and the two arguments- Growing a block safely with
realloc() - Checking for
NULLand whatfree(NULL)does - Returning heap memory from a function
Questions people ask
Do I need an account?
No. Anyone can play. Sign in to keep your XP, streak, badges and history.
Can I retake it?
Yes. Your best score is kept, and the questions and answers are shuffled each time.