OA. free
Free
MathWorks Core Computer Science Core Computer Science Medium

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

Choose one option.
Show answer & explanation
Answer: A. Calloc initializes the allocated memory with 0 (zero) while malloc just fills it with garbage

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:

  1. 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
  2. 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)
  3. 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