</>EmbeddedInterview

What happens when malloc(4 KB) is called on ARM64 Linux?

MediumARM Architecture

Short answer: The allocator may reuse a free chunk or obtain virtual memory via brk/mmap. A first write to an unbacked anonymous page can fault, causing Linux to allocate a physical page and update the mapping. Allocation is not necessarily page-aligned.

mallocAllocatorbrk / mmapIf neededPage faultIf unbackedPhysical pageRetry
char *p = malloc(4096);
if (p) { p[0] = 'A'; free(p); }

1. Allocator: malloc is a libc function, not a syscall. It checks existing free chunks and may return a pointer without entering the kernel.

2. Virtual memory: If needed, glibc obtains more space through brk or mmap. The kernel creates or extends virtual mappings.

3. First write: A store to an unbacked anonymous page can trigger a page fault. Linux checks the VMA, allocates and zeroes physical memory as needed, updates page tables and retries the instruction.

MOV X0, #4096
BL malloc
CBZ X0, failed
MOV W1, #65
STRB W1, [X0]
failed:

4. Important details: ARM64 Linux may use 4, 16 or 64 KiB base pages. A 4096-byte allocation need not be page-aligned, and allocator metadata can touch pages before the application does. free may retain memory in the allocator.

Interview takeaway: Virtual allocation and physical backing are separate; demand paging often defers physical allocation until access.

Why a 4096-byte allocation does not equal one physical page

Suppose malloc returns virtual address 0x40001020. The requested interval of 4096 bytes ends just before 0x40002020. With 4 KiB pages, it spans two pages because the starting offset is 0x20. The allocator may already have mapped and touched either page. An initial write can generate a minor fault for anonymous demand allocation; later accesses usually reuse the established mapping.

On a Linux system, compare virtual versus resident usage using /proc/PID/maps and /proc/PID/smaps or smaps_rollup. Use getconf PAGESIZE to check the configured page size. The allocator can reuse freed chunks without returning them to the kernel immediately; a large mapping may instead be unmapped, depending on allocator behavior.

Virtual memory overcommit means a successful allocation does not universally guarantee that every future page touch can be backed under memory pressure. Also, physically contiguous backing is not guaranteed. For DMA in a Linux driver, allocate/map using the kernel DMA API, rather than treating a malloc pointer as a bus address.