gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > Dynamic memory allocation on the GBA ?

#4431 - Shadow - Mon Mar 31, 2003 2:25 am

Hi.

I have seen on some other posts something about problems using dynamic memory allocation (malloc, calloc, etc...) on the GBA, and I was wondering why. As far as I know, it is a very useful and powerful technique, especially when it comes to making games.
So, is it possible (recommended) to use dynamic memory allocation on the GBA ? Does the GBA even have (and use) a heap ? If so, where is it located in memory and what is its size ? And finally, if it is too troublesome to use, how do you get things done without it (linked lists, dynamic arrays, etc...) ?

Thanks in advance.

#4440 - tepples - Mon Mar 31, 2003 8:40 am

Shadow wrote:
So, is it possible (recommended) to use dynamic memory allocation on the GBA ?

It's possible, but it's not recommended in general unless you have an algorithm that requires it. It's best to lay out video back buffers, etc. at some fixed location in RAM. And when possible, use either a

Quote:
Does the GBA even have (and use) a heap ?

The BIOS does not have memory allocation functions, but the malloc() implementation linked into some programs allocates from EWRAM.

Quote:
if it is too troublesome to use, how do you get things done without it (linked lists, dynamic arrays, etc...) ?

Here are some good dynamic allocation strategies, each designed to cause much less external fragmentation vs. the typical chained-blocks structure:

  • Stack (freeing blocks in reverse order of allocation)
  • Tower (freeing all blocks allocated after this one, good for a linked list that you use during each frame and then destroy when you're done with it)
  • FAT (allocate in large fixed-size clusters about 1 KB in size, and keep a linked list of clusters in use by a block)


Quote:
Thanks in advance.

Pun intendo? ;-)
_________________
-- Where is he?
-- Who?
-- You know, the human.
-- I think he moved to Tilwick.

#4449 - Paul Shirley - Mon Mar 31, 2003 1:50 pm

The malloc heap usually occupies the whole of EWRAM but GBA programmers have a nasty habit of directly accessing EWRAM. Collisions aren't pretty.

You need to allocate blocks of EWRAM with the __attribute__((section)) system, the linker will then keep the heap away from your direct allocations and its safe to use malloc/new.

On a fixed size memory machine avoiding dynamic memory is usually good advice for reasons of efficiency and stability. Memory leaks are annoying on a PC but fatal on a Gameboy, the same applies to memory fragmentation.