Search code examples
cassemblyatt

memory address of a struct data item


Given the following struct:

typedef struct {
  char a;
  int b[10];
} elem;

elem s[100];

and knowing that s, i, and j are located in %ebx, %esi, and %edi respectively, how do I determine the memory address of

s[i].b[j]

?

Thank you!


Solution

  • That's pretty easy:

    • The address of s[i] is offset from the address of s[0] by i * sizeof(elem) bytes.

    • The address of the member b[j] is offset from the member b[0] by j * sizeof(int) bytes.

    • The address of b[0] inside an object elem x is offset from the address of x by offsetof(elem, b) bytes. You need to #include <stddef.h> for this macro.

    You can write a C program to emit all the relevant constants and then use those in your assembly code. In any case, you want to compute:

    s + i * sizeof(elem) + offsetof(elem, b) + j * sizeof(int)
    

    Or:

    ebx + esi * sizeof(elem) + offsetof(elem, b) + edi * sizeof(int)