cmallocsdccretro-computing

SDCC and malloc() - allocating much less memory than is available


When I run compile this code with SDCC 3.1.0, and run it on an Amstrad CPC 464 (under emulation, with WinCPC 0.9.26 running on Wine):

void _test_malloc()
{
  long idx = 0;
  while (1)
    {
      if (malloc(5))
    {
      printf("%ld\r\n", ++idx);
    }
      else
    {
      printf("done");
      break;
    }
  }
}

... it consistently taps out at 92 malloc()s. I make that 460 bytes, which leads me to a couple of questions:


Solution

  • In fact, as Duncan Bayne says, there is a very narrow heap space in the default memory manager that SDCC implements for Z80.

    However, before trying to modify SDCC's heap, you should consider if you actually need dynamic memory on an Amstrad CPC. Generally, there is no point on using dynamic memory when you run a stand-alone application, which owns the entire hardware. You can test and know how much memory you have, and you can directly write to memory wherever you wanted. There is no memory protection, and no other applications running on background.

    Therefore, is much preferable for you to design your own memory map (where you want your data to be and how much space to use) and then directly manage the memory. Moreover, code optimization is much important in this machine, and manually managing memory is extremelly relevant for optimization.

    If your code is running directly in the Amstrad CPC (i.e. not using a modern OS like Symbos), you have to manually deal with bank switching to access memory. Z80 CPU has a 16-bits bus, which can only address 64KB of memory without bank switching.