Google Interview Question: Implement an Aligned Memory Allocator and Free Function

12 Views
No Comments

“””
Write a memory allocation function (and corresponding free function)
that returns a block of memory aligned to the specified alignment value.
You may assume that the alignment is a power of 2 (1, 2, 4, 8, 16, …).
“””

This Google systems-level question asks you to implement your own malloc-like function that guarantees the returned pointer is aligned to a given power-of-two boundary. Because standard malloc does not guarantee arbitrary alignment, you typically over-allocate a bit, adjust the returned pointer upward to the next aligned address, and store metadata (often the original malloc pointer) right before the aligned region so that your free function can later release memory correctly.

END
 0