News:

MASM32 SDK Description, downloads and other helpful links
MASM32.com New Forum Link
masmforum WebSite

Questions about arrays and stacks

Started by Kyoy, May 17, 2005, 01:12:51 PM

Previous topic - Next topic

Kyoy

Hi all. I am more familiar with C/C++ and i want to know how stack frames and stack pointer works in relation to structures/arrays and local variables in assembly.

For local variables, i know the way to set up a stack frame manually is typically push ebp, mov ebp,esp followed by allocating space for local variables. What happens when you need to allocate for array and structures? I know that the local variables are usually placed between ebp [ebp+00] and esp [ebp-xx]

This is what i don't understand. Say there are 3 elements. Will the first element of the array be placed at [ebp-04] or [ebp-0C] ? Similiarly, will the last element of the array be placed at the higher or lower offset?

I know i can use invoke and all that, i just want to know this for curiousity sake. Please help out, thanks.

chep

Hi,

Arrays on the stack are handled the same way as anywhere else in memory : higher indexes are at higher offsets.

So having only a 3 DWORD array in the stack frame (push ebp / mov ebp, esp / sub esp, 0Ch), element 0 will be at [ebp-0Ch], element 1 at [ebp-08h] and element 2 at [ebp-04h].
BTW the same applies to structures :wink

Jeff

to further elaborate, all local variables are aligned at 4 byte boundaries in general.
consider the following:

procedure1 PROC
LOCAL array[4]:DWORD
...
procedure1 ENDP

array begins at [ebp-10h]
array[0]          [ebp-10h]
array[1]          [ebp-Ch]
array[2]          [ebp-8h]
array[3]          [ebp-4h]
esp                 [ebp-10h]

procedure2 PROC
LOCAL array[4]:WORD
...
procedure2 ENDP

array begins at [ebp-8h]
array[0]          [ebp-8h]
array[1]          [ebp-6h]
array[2]          [ebp-4h]
array[3]          [ebp-2h]
esp                 [ebp-8h]

procedure3 PROC
LOCAL array[4]:BYTE
...
procedure3 ENDP

array begins at [ebp-4h]
array[0]          [ebp-4h]
array[1]          [ebp-3h]
array[2]          [ebp-2h]
array[3]          [ebp-1h]
esp                 [ebp-4h]

procedure4 PROC
LOCAL array[3]:BYTE,var:WORD
...
procedure4 ENDP

array begins at [ebp-4h]
array[0]          [ebp-3h]
array[1]          [ebp-2h]
array[2]          [ebp-1h]
var                 [ebp-6h]
esp                 [ebp-8h]

bigger STRUCT
    b1 BYTE ?
    b2 WORD ?
bigger ENDS

procedure5 PROC
LOCAL array[3]:bigger,var:DWORD
...
procedure5 ENDP

array begins at [ebp-Ch]
array[0].b1     [ebp-Ch]
array[0].b2     [ebp-Bh]
array[1].b1     [ebp-9h]
array[1].b2     [ebp-8h]
array[2].b1     [ebp-6h]
array[2].b2     [ebp-5h]
var                 [ebp-4h]
esp                 [ebp-10h]


man i hope i got all that right.  :)