2

How can I store variables in an array, which size is known only on run-time? How can I access elements of this array? I think it should be easy, but I don't see a way.

I mean something like dynamic arrays in C.

Ivan
  • 609
  • 8
  • 21

3 Answers3

0

You could also allocate memory with a static size on stack at the beginning of your function:

proc yourFunction stdcall param1:DWORD
local yourData[256]:BYTE
  ;...
endp

It has the disadvantage of having a static size (256 bytes in the example above) but you don't have to call plattform specific APIs like VirtualAlloc and it is cleaned up when you leave your function (no need to keep track of your allocated data and call VirtualFree()).

Christian Ammann
  • 888
  • 8
  • 19
  • Or you can `sub rsp, rax` to reserve a run-time variable amount of stack space, like you'd get from a C compiler for a function with a local C99 variable-length array. – Peter Cordes Jul 01 '16 at 15:30
0

For WinAPI this would be sth like:

invoke HeapAlloc, hHeap, flags, size
mov    [pointer], eax

For more information see this (HeapAlloc)
https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapalloc
and this (Heaps in Windows)
https://learn.microsoft.com/en-us/windows/win32/api/heapapi/

Dima Rich
  • 61
  • 6
0

You don't state which operating system, but under Windows, VirtualAlloc is an easy way of allocating coarse blocks of memory. It returns a pointer which you can load into a register and use as a base address.

invoke  VirtualAlloc,NULL,size,MEM_COMMIT+MEM_RESERVE,PAGE_READWRITE
mov     [eax],something
Jens Björnhager
  • 5,632
  • 3
  • 27
  • 47