What does malloc(n) return?
malloc() does not clear the memory – it contains whatever was there before. When there is not enough memory it returns NULL, so every call must be checked.
Memory Allocation · Exercise 1 of 4
Twelve multiple-choice questions on malloc, calloc, realloc and free, stack vs heap, memmove, alignment and C23. Pick an option to check your answer instantly.
What does malloc(n) return?
malloc() does not clear the memory – it contains whatever was there before. When there is not enough memory it returns NULL, so every call must be checked.
Which statement about calloc(count, size) is true?
calloc() clears the block to zero bytes and checks the multiplication. A plain malloc(count * size) can wrap around to a small number and return a block far smaller than you think.
What happens when you call free(NULL)?
The standard says free(NULL) has no effect. That is why setting a pointer to NULL after freeing it makes an accidental second free() harmless, and why cleanup code can free pointers that were never allocated.
If realloc(p, bigger) cannot get the memory, what happens?
The old block stays valid and still has to be freed. That is why p = realloc(p, n) is a leak on failure – store the result in a temporary pointer and assign it only when it is not NULL.
Which situation is a memory leak?
A leak happens when the last pointer to a heap block is lost – overwritten, or gone out of scope – before free(). The memory stays reserved until the program ends.
In void f(void) { int x; int *p = malloc(sizeof *p); }, where are x, p and the allocated int?
x and the pointer variable p are locals (stack) and vanish when f returns. The block p points to is on the heap and survives – here it leaks, because nothing frees it before p disappears.
Why is p = malloc(n * sizeof *p); preferred over p = malloc(n * sizeof(int));?
sizeof *p is worked out from p's declaration and does not dereference anything at run time. If p later becomes a long * or a struct pointer, the allocation is still the right size.
Is int *p = (int *) malloc(n * sizeof *p); necessary in C?
In C, void * converts implicitly. The cast is harmless today but redundant, and in C89 it could hide a missing #include <stdlib.h>. C++ does not allow the implicit conversion.
What happens if the source and destination of memcpy() overlap?
memcpy() may copy in any order (and very fast), so overlapping data can be corrupted. memmove() is defined to behave as if it copied through a temporary buffer.
In C23, what is realloc(p, 0)?
Implementations disagreed about realloc(p, 0) (free and return NULL, or return a small block), so C23 made it undefined. To release memory, always use free().
Timed online tests with instant scores and explanations.