Skip to content

Reducing Code Size

Tom Sherman edited this page Feb 26, 2017 · 30 revisions

Determining Minimum Size of the Heap

In order to use malloc, calloc, realloc it is necessary to call initHeap located in system.h. This is typically done a single time at the beginning of your program. A typical example would be:

static char heap[10000];
static bool init_run = false;

void init()
{
    initHeap(heap, heap + sizeof(heap));
    ...
}

void _main()
{
    if (!init_run)
    {
        init();
        init_run = true;
    }

    ...
}

This would create a 10,000 byte heap for the rest of the program to use. Any call to malloc, calloc, realloc will allocate a pointer somewhere in the memory region that heap[10000] occupies. If initHeap is called again, the new heap will be used and the previous one will be essentially forgotten about.

When the heap is initialized this way, the heap is contained in one of the memory regions supplied in the config file for wiimake. This means that an excessively large heap will limit how much code you can inject. On the other hand, a heap that is too small will result in many failed calls to malloc, calloc, realloc. (Note: in order to write stable code you should always handle the possibility of memory allocation failing). Thus, it is extremely important to choose the 'right' size of your heap. Here are some steps you can take to determine how large the heap should be.

First, you must account for the memory that is allocated internally in the MeleeModdingLibray.

print() - The stream that print writes to is allocated on the heap. Memory is not allocated until print() is called (note: calling error() does not cause memory to be allocated). Each line of display takes up 96 bytes. The maximum number of lines is capped at 27 or until the stream takes up 1/5 of the heap size. This means, in order to have all 27 lines available to display you need a heap of size: 96 * 27 * 5 = 13000. Usually most applications need only a few lines at a time. 96 * num_lines * 5 = size_of_heap

One possible way to avoid this is to shrink Melee's heap and use that space, for more information see the next section titled "Shrinking Melee's Heap".

Choosing the correct size for the heap is extremely important.

Shrinking Melee's Heap

Compiler Optimization

Function Size