20.
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
20. (C Question) Dynamic memory allocation
With respect to the differences between malloc and calloc, select the option(s) that are true.
Pick ONE OR MORE options
Show answer & explanation
Calloc initializes memory to zero, while malloc leaves it uninitialized (garbage). Calloc's signature is calloc(count, size) taking number of elements and element size, while malloc(bytes) takes total bytes. Both malloc and calloc always allocate contiguous memory—options B and D are reversed/incorrect.
Step-by-step Derivation:
Key differences between malloc and calloc:
Initialization: calloc zeros out memory; malloc does not (contains garbage).
- malloc(100) → uninitialized 100 bytes
- calloc(10, 10) → 100 bytes initialized to 0
- Option A is TRUE
Contiguity: Both malloc and calloc guarantee contiguous memory allocation. This is a requirement of both functions in the C standard.
- Options B and D are FALSE (they incorrectly suggest malloc may not be contiguous)
Function signatures:
- malloc(size_t bytes) → takes number of bytes
- calloc(size_t count, size_t element_size) → takes count and element size
- Option C is TRUE
Correct answers: A and C