RISC-V Assembly Language - Heap

If you are using the RISC-V simulator RARS, you can request heap memory directly from the simulator's runtime environment using ecall.

Syscall Code: 9 (Sbrk / Allocate Heap)
Input:a0 = Number of bytes to allocate
Output:a0 = The base memory address of the newly allocated chunk

.text .global main main: # 1. request 16 bytes of heap memory li a7, 9 # syscall code - 9 (sbrk) li a0, 16 # load requested size (16 bytes) ecall # syscall # a0 now holds the address of the allocated heap space # 2. store data into the allocated heap space li t0, 42 # Load a dummy value (42) into t0 sw t0, 0(a0) # Store the value 42 at the beginning of the # heap chunk (offset 0) li t1, 99 # Load another dummy value (99) into t1 sw t1, 4(a0) # Store the value 99 at the next word (offset 4) # 3. exit program li a0, 0 # Return code 0 li a7, 93 # syscall - Exit ecall # syscall

Note: In RARS there is no de-allocation system call. You have the heap memory for the duration of the running program. However, unlike the stack, you can ask for as many bytes as we want without considering alignment.