Search code examples
cassemblyy86

How do you allocate space well for multiple arrays in Y86 assembly?


I am trying to convert C code into Y86 assembly code.

What happens if you have multiple array declarations such as:

int a[100], b[100];

Suppose every integer is 4 bytes. How do you know where in memory to point for the pos. directives so that you do not waste any space?

<Assembly code begins here>

...

halt

# Array initialization begins here
.pos ?
A:
.long 0

.pos ?   
B:
.long 0

Solution

  • Let the assembler worry about the offsets.
    One possibility is to define a struct that contains local variables

    struc Locals
        a dd ? dup 100
        b dd ? dup 100
    ends Locals
    
    sub esp, sizeof Locals ;; or perhaps sizeof struc Locals
    mov ebp, esp           ;; take a copy of stack ptr
    
    mov eax, [ebp + offset a] ;;  
    mov ebx, [ebp + offset b] ;;  
    

    In gcc the meaning of 'struct' is to modify the absolute position of current segment without introducing linkable code:

    .file "temp.c"
        .struct 0
    a:  .struct a + 4*100
    b:  .struct b + 4*100
    c:               ;; c will contain expression for the size
        .struct 0    ;; you can start a new struct here
    a2: .struct a2 + 4   ;; this struct would be  'int a2;'
    b2: .struct b2 + 8   ;;  'double b2'
    c2:                  ;; sizeof struct #2
    
    .text  
        sub c, %rsp
        mov $13, a(%rsp)   ;; a[0] = 13
        mov $2,  b(%rsp)   ;; b[0] = 2