release
dev builds
extras
themes manual
wiki
device status forums
mailing lists
IRC bugs
patches
dev guide



Search | Go
Wiki > Main > WhyNoMalloc (r1)

Why are we not using malloc() in Rockbox?

One of the first things that stump many developers coming into Rockbox is the lack of malloc(). Dynamic memory allocation is so common in "normal" programming that some people find it difficult to adjust their mindset to the concept of no-malloc programming.

So what are the reasons we don't want to use malloc?

1: Always use all the ram

We want to maximise the size of the audio buffer in order to minimise the requirements for harddisk access (hd spinup uses a lot of power). This translates into longer battery life.

Dynamic memory requires a heap, the area of unused memory from where malloc grabs the memory your code is requesting. This means there must always be unused memory available, i.e. we cannot at any time use all of the available memory on the device. This means a smaller audio buffer, more spinups and hence shorter battery life.

2: Never run out of memory

We don't want Rockbox to ever say "Out of memory". We want to know exactly what our worst-case memory situation is. And we want to make sure we can handle it. The heaviest music codec, the largets playlist, the most hairy id3 tags, the biggest plugins -- all at the same time.

This can in theory be accomplished in a system with dynamic memory allocation too, but it is very difficult and requires advanced runtime analysis and tools. With static allocation the compiler will simply refuse to compile if we use too much memory.

3: Easier to debug

With dynamic memory allocation, you have a whole class of bugs related to mistakes in allocation, freeing and pointer management. Memory leaks, for example, can be very difficult and time consuming to track down and fix.

With static memory allocation, memory leaks are simply not possible. Of course we still use pointers, and occasionally write buggy pointer code. But it's a lot easier to debug.

4: Promoting economical programming

Developers whose experience chiefly derives from Windows or Unix programming are not always used to thinking economically about memory use. Being forced to allocate every buffer statically in your code, to the maximum supported size, tends to have the effect of questioning and analysing the need for each buffer and byte.
Edit | Attach | Print version | History: r4 < r3 < r2 < r1 | Backlinks | View wiki text | More topic actions...
r1 - 21 Jun 2007 - 10:08:00 - BjornStenberg
Copyright by the contributing authors.