Heap

From Boktai Hacking Wiki
Revision as of 21:38, 7 May 2025 by Raphi (talk | contribs) (Created page with "The heap is used for ''dynamic'' memory allocation (mostly, but not only, actors). This contrasts with ''statically'' allocated data like maps or save data, which have fixed memory addresses. Usage of the heap is based on the common C functions [https://manpages.debian.org/stable/manpages-dev/malloc.3.en.html malloc() and free()], although their implementation in Boktai is far simpler than what is found on modern systems. malloc() returns NULL if there's not e...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The heap is used for dynamic memory allocation (mostly, but not only, actors). This contrasts with statically allocated data like maps or save data, which have fixed memory addresses. Usage of the heap is based on the common C functions malloc() and free(), although their implementation in Boktai is far simpler than what is found on modern systems.

malloc() returns NULL if there's not enough space left in the heap, and the games do check for this condition in most (all?) calls.

The heap in Boktai uses a doubly-linked list of blocks. Each block can either be allocated or free. When the game starts, it creates one big free block in EWRAM. The first malloc() call will then split this block into a smaller, allocated, block to fulfill the allocation request, and a new free block of the remaining size.

struct HeapBlock {
        HeapBlock* prev;
        HeapBlock* next;
        // Top bit: 0=allocated, 1=free
        u32 size_and_flag;
        u32 padding;

        // Content of this block follows:
        u8 data[];
};
Game Heap start (first block) Heap size
Boktai 1 (U) 0x02000000 105 KiB
Boktai 2 (U) 0x02000000 129 KiB
Boktai 3 (J) 0x02000714 ≈123.2 KiB