Question 9: Memory Allocation Which of the following is true regarding heap dynamic memory...
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Question 9: Memory Allocation
Which of the following is true regarding heap dynamic memory allocation?
- When malloc allocates the block, it allocates extra bytes to hold metadata containing the size of the block.
- The free block list is maintained as a linked structure.
Show answer & explanation
Statement 1 is correct: malloc implementations allocate extra metadata (typically a header) before the user-accessible memory to store the block size, which is essential for the free() function to know how many bytes to deallocate. Statement 2 is correct: free memory blocks are typically managed using a linked list (or more sophisticated structures like binning), where each free block contains a pointer to the next free block, allowing the allocator to traverse and coalesce free regions efficiently.
Step-by-step Derivation:
Both statements describe standard practices in heap memory management: (1) Metadata storage—malloc prepends a header containing block size and potentially other bookkeeping info (alignment, magic numbers) to each allocation; (2) Free list maintenance—the allocator maintains a linked structure of free blocks (e.g., first-fit, best-fit algorithms traverse this list to find suitable blocks for allocation or coalesce adjacent free blocks during deallocation). Therefore, the correct answer is C.