push 4*10; Number of bytes to allocate(executable NetRun link)
extern malloc
call malloc
add esp,4; Undo "push"
; Malloc's return value, a pointer, comes back in eax.
... ; use eax as array here
; Eventually, you'll need to call "free" to release that memory:
push eax
extern free
call free
add esp,4; Undo "push"
sub esp,4*10; Make space on the stackC/C++ of course can't directly access the stack pointer, but there's often a compiler-builtin function called "alloca" (which looks suspiciously like malloc!) that allocates a user-defined amount of space on the stack. Unlike malloc, memory allocated with alloca is automatically freed when the function returns. "alloca" may not exist on all machines, since some machines have rather funky stacks.
mov eax, esp; Point eax to the start of that space
... ; Use eax as array here
add esp,4*10; Restore stack
mov eax,thingy; Point eax to thingy's data
...
section .bss; <- Uninitialized (but writeable!) data area
thingy:
resb 4*10; Reserve this many bytes of space here
Allocation Method |
Allocation Speed |
Storage Available |
Assembly Example |
Disadvantages |
malloc/free |
Slow (100ns) |
Gigabytes |
push 100 call malloc |
Must remember to call free |
stack or alloca |
Fast (1ns) |
Megabytes |
sub esp,100 mov eax,esp |
Must remember to move stack pointer back; storage is limited to stack size; alloca() not always available in C/C++ |
"section" |
Not needed (fixed allocation!) |
Megabytes |
mov eax,my_pointer my_pointer: resb 100 |
Wastes space even when not in use; usually not "threadsafe" |