user1114371
user1114371

Reputation: 89

array and assembly

If I declare these 3 arrays

int a[10][10];
int b[10][15];
int c[10][30];

For which of these three arrays, would the assembly code return the [i][j] element? Assuming that the starting address of the array is stored in %ebx.

pushl   %ebp
movl    %esp, %ebp
movl    8(%ebp), %edx          /* index i */
movl    12(%ebp), %ecx         /* index j */
movl    %edx, %eax
sall    $4, %eax
subl    %edx, %eax
addl    %ecx, %eax
movl    (%ebx,%eax,4), %eax
popl    %ebp
ret

How do you solve this type of questions

Upvotes: 1

Views: 1801

Answers (2)

icyrock.com
icyrock.com

Reputation: 28608

I'd approach this by doing some hand-written math with notes, such as this:

movl    8(%ebp), %edx          /* index i */
-> edx = i
movl    12(%ebp), %ecx         /* index j */
-> ecx = j
movl    %edx, %eax
-> eax = i
sall    $4, %eax
-> eax = 16 * i
subl    %edx, %eax
-> eax -= i, thus:
-> eax = 16 * i - i = 15 * i
addl    %ecx, %eax
-> eax += j, thus: 
-> eax = 15 * i + j 
movl    (%ebx,%eax,4), %eax
-> eax = array[4 * eax], thus:
-> eax = array[sizeof(int) * (15 * i + j)]

So, in eax at the end you get what's in the given array (pointed by ebx at the beginning) at position 15 * i + j. This can properly address:

  • An int array
  • An array that has 15 for its first (right-most) dimension

Given that and your three arrays:

int a[10][10];
int b[10][15];
int c[10][30];

this addresses b properly, but not a nor c.

Upvotes: 1

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215277

Work backwards from the line that dereferences array:

movl    (%ebx,%eax,4), %eax

Here, 4*eax is used as the offset (where 4 is sizeof(int)) so the value in eax is the number of ints from the beginning of the array. Now write an equation for eax in terms of the arguments read off the stack...

Upvotes: 0

Related Questions