Allocation on the stack

By Grauw

Ascended (10581)

Grauw's picture

07-12-2014, 16:17

If you wish to allocate on the stack, like C does, with hl, ix or iy pointing to the new object:

    ; allocate on stack
    ld ix,-MyObject_size
    add ix,sp
    ld sp,ix

    ; deallocate from stack
    ld ix,MyObject_size
    add ix,sp
    ld sp,ix

Or, generalised as macros:

stack_alloc: MACRO ?reg, ?size
    ld ?reg,-?size
    add ?reg,sp
    ld sp,?reg
    ENDM

stack_dealloc: MACRO ?reg, ?size
    ld ?reg,?size
    add ?reg,sp
    ld sp,?reg
    ENDM

Probably always want to use hl for deallocation, as you’re most likely not using the resulting value.

Nice little tidbit Smile.

Login or register to post comments

By PingPong

Prophet (3889)

PingPong's picture

08-12-2014, 21:45

nice

By Grauw

Ascended (10581)

Grauw's picture

21-01-2016, 22:06

Wanted to repost this great snippet from msd here:

msd wrote:

A while ago I made a function to allocate space on the stack, which is automatically cleaned when you exit a function

AllocateStackSpace:
; Input
; 		BC = Size to allocate
; Output :	HL = Pointer to allocated stack space
;	
; Mofifies BC,HL,IX
		POP	IX			; Get return address
		LD	HL,0
		ADD	HL,SP
		OR	A,A
		SBC	HL,BC
		LD	SP,HL
		PUSH	BC			; Store object size on stack
		LD	BC,FreeStackSpace
		PUSH 	BC			; Free stack function on stack
		JP	(IX)
		
FreeStackSpace:
		POP	HL	; Get object size
		ADD	HL,SP
		LD	SP,HL	; Restore Stack
		RET

This function is the first function you need to call before any other push or pop.

It can be used as follows

  Test:
		LD	BC,100
		CALL	AllocateStackSpace
                ; HL points too allocated space          
                RET