Memory

The Atari Lynx memory map, the C runtime stack and stack-overflow checking, and the dynamic-memory (heap) allocator.

1. Memory layout

cc65 generated programs with the default setup run with the I/O area and the kernal enabled, which gives a usable memory range of $200 - $C037.

Special locations (default lynx.cfg):

  0000 - 00FF  Zero page
  0100 - 01FF  Machine stack (6502 hardware stack)
  0200 - C037  Program, data, heap and C stack (MAIN area)
               ($A058 - $C037 is the collision buffer under lynx-coll.cfg)
  C038 - E017  Screen buffer 1
  E018 - FFF7  Screen buffer 0   (shares addresses with the I/O overlay)
  FC00 - FFF7  Suzy / Mikey / boot-ROM overlay -- CPU view only
  FFF8 - FFFF  Hardware vectors and MAPCTL

The $E018–$FFF7 and $FC00–$FFF7 lines overlap on purpose: that is one physical block of DRAM holding screen buffer 0, but at those same addresses the CPU sees Suzy, Mikey and the boot ROM. It is not a conflict — the display and the sprite engine reach that RAM by a different path than the CPU, so the buffer and the registers coexist. Section 2 explains how.

The same map is shown below. With the default config (lynx.cfg) the program, heap and C stack share the RAM below the screen buffers; the __STACKSIZE__ reservation (1 KB by default) sits at the very top of that area, just under the first screen buffer:

$FFFF $FFF7 $E017 $C037 $BC38 $0200 $0100 $0000 Hardware vectors Screen buffer 0 Screen buffer 1 C runtime stack grows ↓ free RAM — heap grows ↑ Program code & data 6502 hardware stack Zero page __STACKSIZE__ = $0400 (1 KB) STARTUP · CODE · RODATA · DATA · BSS (MAIN segment)
Default memory layout (lynx.cfg) — regions not to scale. Only a small resident stub of STARTUP stays in memory; the crt0 one-shot init (ONCE) sits at the floor of the free-RAM/heap region and is reclaimed by the first allocation.

When collision detection is enabled (lynx-coll.cfg) a 2 KB collision buffer is carved out below the screen buffers, so the usable program area and the top of the C stack move down to $A057:

$FFFF $FFF7 $E017 $C037 $A057 $9C58 $0200 $0100 $0000 Hardware vectors Screen buffer 0 Screen buffer 1 Collision buffer C runtime stack grows ↓ free RAM — heap grows ↑ Program code & data 6502 hardware stack Zero page __STACKSIZE__ = $0400 (1 KB) STARTUP · CODE · RODATA · DATA · BSS (MAIN segment)
Layout with collision detection (lynx-coll.cfg) — regions not to scale. As with the default layout, the crt0 one-shot init (ONCE) sits at the heap floor and is reclaimed once main() begins allocating.
Text screen

There is no conio support: the Lynx has no text mode. Text output goes through the Lynx graphics bitmap-font functions (gfx_outtext, gfx_outtextxy).

Keyboard

There is no keyboard. The Opt 1, Opt 2 and Pause switches are joypad inputs, reported by joy_read() together with the d-pad and the A/B buttons (masks JOY_OPT1_MASK, JOY_OPT2_MASK, JOY_PAUSE_MASK in lynx/lynx.h). The classic conventions Pause+Opt 1 = restart and Pause+Opt 2 = flip screen are game conventions for the application to honor.

Stack

The C runtime stack is located at $C037 (or $A057 if collision detection is enabled) and growing downwards.

Heap

The C heap is located at the end of the program and grows towards the C runtime stack. Its first bytes are the ONCE segment — the crt0 one-shot startup code, which runs once before main() and is then reclaimed: the first allocation grows the heap straight over it. Only a small resident stub of STARTUP (the reset entry, the _exit trap and a relocator) stays permanently in memory. See §4 and design/LYNX_STARTUP_RECLAIM_DESIGN.md.

Screen

The collision detection screen is at $A058 if it is enabled. The double buffered screens are at $C038 and $E018; see Graphics → Frame buffers for the two 8160-byte pages and how double buffering flips them.

Maximum program size

The MAIN segment (STARTUP, CODE, RODATA, DATA, BSS, and the reclaimable ONCE one-shot startup code that the heap grows over), the C heap and the C stack all share the RAM below the screen buffers — $0200 - $C037, which is $BE38 (48,696) bytes in total. With the default 1 KB stack that leaves $BA38 (47,672) bytes for code, data and heap combined. With collision detection (lynx-coll.cfg) the shared region shrinks to $0200 - $A057, so code, data and heap must fit in $9A58 (39,512) bytes. This is a hard ceiling: the linked program is copied into RAM at boot, and there is no usable RAM above the screen buffers.

The ONCE one-shot startup code counts against this ceiling only at boot. Once main() begins allocating, the heap grows straight over it and those bytes — __ONCE_SIZE__, 137 ($89) bytes in the default build and growing with each module constructor (for example 155 bytes when the heap allocator's own constructor is linked in) — are returned to the heap and become available for allocation. So the effective budget for code and data is the figure above plus the reclaimed ONCE region, which is handed back as free heap.

A cart can hold far more than this — 128, 256 or 512 KB (see Cart ROM and EEPROM) — but only that ~47 KB RAM image is directly addressable. Anything beyond it (extra levels, graphics, audio banks or code overlays) has to be streamed from the cart at run time with the cart file API (openn, read, lseek, lynx_load), not linked into the program image.

2. Memory-mapped I/O and the display overlay

The map in §1 has an apparent impossibility in it: screen buffer 0 occupies $E018–$FFF7, yet that same range is where the CPU finds Suzy, Mikey and the boot ROM. The two do not actually collide, because the top of memory is reached by three different bus masters over three different paths — and only one of them sees the hardware overlay.

The 64 KB is a single physical DRAM array. What answers at $FC00–$FFFF depends on who is asking:

The CPU — through the MAPCTL decoder

Only the CPU is subject to the overlay, and the MAPCTL register at $FFF9 decides what it sees. Each of the four low bits disables one overlay window and exposes the RAM underneath: SUZYSPACE ($FC00–$FCFF), MIKEYSPACE ($FD00–$FDFF), ROMSPACE ($FE00–$FFF7) and VECTORSPACE ($FFF8–$FFFF) — the masks are defined in <lynx/lynx.h>. crt0.s programs MAPCTL = $0C, which disables the ROM and vector windows (the boot ROM only matters at reset, and the CPU then fetches its interrupt vectors from RAM) but leaves the Suzy and Mikey windows enabled. So from the CPU's side the only part of screen buffer 0 hidden behind hardware is the 512-byte strip at $FC00–$FDFF: a plain sta $FD00 writes a Mikey register, not a pixel.

Mikey's video DMA — straight to DRAM

The circuit that refreshes the LCD reads the frame buffer directly from physical DRAM, starting at scrbase ($FD94), and ignores MAPCTL entirely. It scans $E018–$FFF7 out as pixels no matter what the CPU sees at those addresses.

Suzy's sprite engine — straight to DRAM

When Suzy paints a sprite it reads the SCB and sprite data and writes the rendered pixels to the buffer as its own DMA accesses to physical DRAM, again bypassing MAPCTL. Suzy can write $FC00–$FFF7 as RAM even though those addresses are registers to the CPU.

CPU sees the overlay Suzy sprite engine Mikey video DMA MAPCTL decode $FFF9 Hardware registers CPU view only Suzy  $FC00–$FCFF Mikey $FD00–$FDFF Physical DRAM Screen buffer 0 $E018–$FFF7 reached directly, ignoring MAPCTL window enabled window disabled → RAM blits pixels → RAM scans RAM → LCD
Three masters, three paths to the same top-of-memory DRAM. Only the CPU goes through the MAPCTL decoder — so it sees Suzy/Mikey registers at $FC00–$FDFF — while Suzy's blitter and Mikey's video DMA read and write the underlying screen buffer directly, ignoring MAPCTL.

This is why the buffer works, and why it is parked here in the first place. Programs never draw pixels with the CPU: they hand Suzy a sprite and a destination and let it blit, and Mikey's DMA reads the result — both go straight to RAM. The CPU only ever writes the registers at $FC00–$FDFF to tell Suzy and Mikey what to do. RAM sitting under a permanent I/O overlay is awkward for the CPU to use — you would have to toggle MAPCTL around every access — so it is the ideal home for something touched only by DMA. Screen buffer 0 stops at $FFF7 precisely so it clears the hardware vectors at $FFF8–$FFFF that the CPU still needs.

3. The C runtime stack and stack-overflow checking

cc65 programs use two independent stacks. The 6502 hardware stack lives in page 1 ($0100–$01FF, a fixed 256 bytes) and holds subroutine return addresses and interrupt state. The C software stack — also called the parameter stack — holds function parameters and local variables; it is addressed through the zero-page pointer sp and grows downwards from the top of the MAIN memory area. The amount of RAM reserved for it is the link-time symbol __STACKSIZE__, which defaults to $0400 (1 KB).

3.1. Setting the stack size

All of the Lynx configs (lynx.cfg, lynx-bll.cfg, lynx-coll.cfg, lynx-uploader.cfg and the fixed-size lynx-128k.cfg / lynx-256k.cfg / lynx-512k.cfg — see Cart §1.1) reserve the stack the same way. They declare a weak symbol and then shrink the MAIN region by exactly that amount, for example in lynx.cfg:

SYMBOLS {
    __STACKSIZE__: type = weak, value = $0400; # 1k stack
}
MEMORY {
    MAIN: file = %O, define = yes, start = $0200, size = $BE38 - __STACKSIZE__;
}

The startup code (crt0.s) then sets the initial stack pointer to the top of that reservation:

sp = __MAIN_START__ + __MAIN_SIZE__ + __STACKSIZE__

so the stack occupies the top __STACKSIZE__ bytes of MAIN and grows down toward your code, data and heap. Because the symbol is weak, the default can be overridden at link time without editing the config — for example to grow it to 2 KB for a recursion-heavy program:

cl65 -Wl --define,__STACKSIZE__=$0800 -o game.lnx main.c

Every byte handed to the stack is a byte taken from code, data and heap, so the goal is to pick the smallest value that still survives the deepest call nesting and the largest local arrays your program uses. There is no automatic overflow protection at this size — if the stack grows past its reservation it silently collides with the top of BSS/heap — unless you enable stack-overflow checking, described next.

3.2. Enabling stack-overflow checking

The compiler can instrument every function with a call to a small checking routine (stkchk/cstkchk in the runtime library). This is off by default. Turn it on for a whole build with the compiler option:

cl65 --check-stack -o game.lnx main.c
cc65 --check-stack main.c          # compiler invoked directly

or enable it only around specific code with the #pragma check-stack, which understands push/pop:

#pragma check-stack (push, on)
/* deeply-recursive or stack-heavy functions here */
#pragma check-stack (pop)

With checking enabled the compiler emits a jsr stkchk at every function entry (the hardware-stack check) and, for functions that allocate locals, a jsr cstkchk after the locals are reserved (the C-stack check). Each routine works against a safety margin rather than the exact limit: cstkchk treats the bottom 256 bytes of the C stack as a reserved zone and aborts once sp descends into it, and stkchk aborts when fewer than 12 bytes of the hardware stack remain. So with checking on, the effective usable C stack is about __STACKSIZE__ − 256 bytes:

C software stack 6502 hardware stack (page $0100) $C037 $BD38 $BC38 usable C stack ≈ 768 B ($300) SP grows ↓ $C037 = initial SP low-water mark 256-byte safety zone cstkchk aborts here $01FF $0100 256 bytes total 12-byte reserve
Stack-overflow checking reserves a 256-byte safety zone at the bottom of the C stack and 12 bytes of the hardware stack — heights not to scale.

If either check trips, the routine resets sp to its initial value and calls _exit(4), so the program aborts. The Lynx has no console, so there is no diagnostic message — the program simply stops — which makes this primarily a development-time aid.

Overhead. The instrumentation is cheap per call but it is paid on every call, including hot loops and recursion. Each call site costs 3 bytes for the jsr, and the routines themselves run in roughly 18 cycles (hardware-stack check) and 21 cycles (C-stack check) on the normal no-overflow path — about 40 cycles for a function that gets both. There is also a one-time cost of well under 100 bytes: the routine is linked once, plus 4 bytes of state and a start-up constructor that records the initial stack pointer. Because of the per-call tax, enable checking while debugging and stack-tuning, then build the release without it.

A practical way to size __STACKSIZE__: build with --check-stack and a deliberately generous stack, exercise the deepest call paths, and tighten the value until checking no longer aborts — leaving the 256-byte safety margin as headroom. See #pragma check-stack in the cc65 manual and the __STACKSIZE__ notes in the ld65 manual for more detail.

4. Dynamic memory allocation (the heap)

Dynamic memory is available through the standard <stdlib.h> functions malloc, calloc, realloc and free. There is no operating system beneath them: the heap is simply a window of RAM in the MAIN area (section 1), bounded below by your program's static data and above by the C-stack reservation (section 3). The allocator is the standard cc65 implementation — a first-fit free list backed by a bump pointer for fresh memory — carrying a deliberately small per-block header for the Lynx's flat 64 KB address space.

4.1. How allocation works

Five runtime variables (declared in <_heap.h>) describe the heap at any moment: _heaporg, the fixed bottom, anchored on __ONCE_RUN__ — the run base of the reclaimable ONCE one-shot startup code, which sits immediately above BSS, so the first allocation grows the heap over the spent crt0 init and reclaims those bytes (see design/LYNX_STARTUP_RECLAIM_DESIGN.md); _heapptr, the bump pointer marking the top of the memory touched so far; _heapend, the ceiling, set once at start-up to sp − __STACKSIZE__ ($BC38 with the default 1 KB stack); and _heapfirst/_heaplast, the two ends of a doubly-linked free list of recycled blocks. Everything between _heaporg and _heapptr has been handed out at least once; everything from _heapptr up to _heapend is still untouched.

Every live allocation carries a two-byte header that holds the block's total size. The pointer you receive points just above that header, so the raw block is always (p − 2) and the size word can be read directly from the two bytes below any valid pointer. When a block is freed and entered into the free list, those same bytes are reinterpreted as a six-byte list node (size, next, prev) — which is why the smallest possible block is 6 bytes and a 1-byte request is rounded up to it. (See design/LYNX_HEAP_HEADER_DESIGN.md for the full layout rationale.)

pointer returned by malloc() / passed to free() p − 2 p size 2 B user data — (size − 2) bytes raw block when freed size next prev unused payload struct freeblock — min 6 B
Every allocation has a 2-byte size header; the returned pointer sits just above it, so the raw block is always p − 2. A freed block reuses those same bytes as a 6-byte free-list node — the smallest block the heap can hold.

malloc() rounds the request up by the two-byte header (and up to the 6-byte minimum), then walks the free list for the first block large enough. A match is either used whole or sliced from its top; if nothing fits, the bytes are carved from the untouched region by advancing _heapptr. If that advance would pass _heapend, the request fails and malloc() returns a null pointer.

free() has a fast path: a block sitting exactly at the heap top is released by simply lowering _heapptr back over it (and if the last free-list block is now at the top, it is absorbed as well). Any other block is inserted into the address-ordered free list and merged with adjacent free neighbours, so that runs of contiguous frees collapse back into one large block instead of fragmenting. The figure below shows the resulting picture: live blocks and free-list holes below _heapptr, untouched space above it, and the C stack descending from the top of MAIN.

$C037 $BC38 _heapptr _heaporg C stack untouched (free to grow) allocated block free-list hole allocated block code · DATA · BSS (static) initial SP _heapend = sp − __STACKSIZE__ top of touched heap bottom of heap = __ONCE_RUN__ (over BSS) stack ↓ heap ↑
The heap occupies the RAM between _heaporg (anchored on __ONCE_RUN__, the reclaimable crt0 one-shot init that sits just above BSS) and the stack reservation (_heapend, $BC38 with the default 1 KB stack). It grows upward through _heapptr — the first allocation reclaims the spent ONCE init — while the C stack grows down from $C037. With no MMU, nothing but --check-stack stops the two from meeting.

realloc() grows or shrinks a block in place when it is at the heap top, and otherwise allocates a fresh block and copies the data over; calloc() is malloc() followed by a zero-fill. Four cc65 extensions round out the API: _heapblocksize() returns the user-visible size of an allocation, _heapmemavail() the total free space, _heapmaxavail() the largest single block that could still be allocated, and _heapadd() donates an arbitrary buffer (for example a static array) to the free pool.

4.2. How it deviates from POSIX

This is a freestanding allocator for a machine with no operating system, no memory-management unit and a 16-bit address space, so it departs from a hosted POSIX environment in several ways worth knowing before you port code onto the Lynx:

5. Startup reclamation and relocation

The whole program image is copied into RAM at $0200 and run in place, so any byte the startup code occupies is a byte lost to code, data and heap for the entire run. Most of what crt0.s does — masking interrupts, programming Mikey and Suzy, setting the C stack pointer, clearing BSS and running the module constructors — happens exactly once, before main(), and is dead weight ever after. Only a tiny part must stay resident: the reset entry at $0200 and the _exit trap that a returning main() (and the stack-overflow checker) lands on. The startup code is therefore split so that the one-time part can be reclaimed by the heap. The full rationale is in design/LYNX_STARTUP_RECLAIM_DESIGN.md.

5.1. The split: resident stub vs one-shot body

crt0.s keeps only a small permanent stub in the STARTUP segment — the $0200 reset jmp, the resident _exit trap, and a short relocator. Everything else moves into the ONCE segment, which runs once and is then grown over by the heap.

Before After STARTUP — IRQ mask · Mikey/Suzy init · sp · zerobss · initlib · _exit 107 bytes — resident forever, trapped at the bottom of MAIN stub ONCE — the one-shot init body jmp · _exit · relocator 27 B · resident runs once, then reclaimed by the heap
The resident startup footprint drops from 107 to 27 bytes; the one-shot init body moves into the reclaimable ONCE segment.

5.2. Relocation and reclaim

There is a catch. The ONCE body has to run at the top of the static area — immediately above BSS, at the heap origin (__ONCE_RUN__) — so the heap can grow over it. But the Lynx copies the file image to RAM verbatim, with no per-segment load step, and a bss-type hole cannot sit in the middle of the image without padding it by the full size of BSS. So ONCE is packed into the image straight after DATA (no hole), which means that after the verbatim copy it lands lower than where it must run — at __ONCE_PHYS__ (which equals __BSS_RUN__ on the plain carts). The permanent relocator copies it up to __ONCE_RUN__ before entering it; the first allocation then overwrites those very bytes.

The whole ONCE segment — __ONCE_SIZE__ bytes, 137 ($89) in the default lynxdemo build and larger as module constructors are linked in (155 bytes in heaptest, for instance) — is therefore reclaimed the moment main() allocates: every one of those bytes is added to the heap and becomes available for the program to use. Nothing above __ONCE_RUN__ stays reserved for startup.

In the image / RAM as loaded (copied verbatim to $0200) Run-time addresses, after the relocator stub LOW CODE RODATA DATA ONCE __ONCE_PHYS__ = __BSS_RUN__ relocator copies up stub LOW CODE RODATA DATA BSS ONCE heap ↑ __ONCE_RUN__ (heap origin) gap zeroed by zerobss
As loaded, ONCE is packed directly after DATA (no bss hole in the image). The relocator copies it up past the BSS gap to __ONCE_RUN__; the heap then grows over it from that same address. On the padded cart-size configs MAIN's fill already lands ONCE at its run address, so __ONCE_PHYS__ == __ONCE_RUN__ and the copy is a harmless self-copy.

5.3. The boot sequence

Putting it together, control flows from the fixed reset entry through the relocator into the relocated body, and finally into main(); the very first allocation reclaims the spent init. The _exit trap the program returns to lives in the permanent stub, so it survives even after the heap has overwritten the ONCE body it was reached from.

Reset @ $0200 — jmp to relocator Relocator — copy __ONCE_PHYS__ → __ONCE_RUN__ onceinit — IRQ mask · Mikey/Suzy · sp · zerobss · initlib push _exit · jmp callmain → main() first malloc() — heap grows over ONCE resident resident in ONCE → _exit is resident ONCE reclaimed
Boot flow. Only the reset entry, the relocator and the _exit trap are resident; onceinit runs from the relocated ONCE copy and is freed once main() begins allocating.