LEA
Load Effective Address :
TL; DR
Compute the absolute or effective address of an offset or memory location and store it in the destination operand without altering any flag.
Consider the following example:
+-----+-----+-----+-----+
| 'h' | 'o' | 'l' | 'a' | <- Valor del array de caracteres "A"
+-----+-----+-----+-----+
| 0 | 1 | 2 | 3 | <-Posición en memoria
+-----+-----+-----+-----+
In C, if we do A[0]
, the returned value should be 'h'
, no? Then, the LEA
instruction in assembler does practically the same, with the difference that the value is not dereferenced , but only the resulting address is loaded in the destination operand.
The following text was taken from a SO response a> .
Imagine you have the following structure:
struct Point {
int xcoord, ycoord;
};
And you define an array of that structure, then you try to access an element of the array by:
int y = points[i].ycoord; /* Accede al elemento en la posicion [i]. */
Then, assuming that the base address, that is, that the element [0]
of the array is in EBX
and the variable i
in EAX
, you have the following instruction:
MOV EDX, [EBX + 8*EAX + 4] ; El lado derecho es la "Dirección efectiva"
And this will result in the value of the variable y
in EDX
; the reason for 8
on the right side is that currently the size of the structure Point
is 8
bytes.
Now consider that you execute the following in your program, instead of assigning the value, you assign the memory address of the variable ycoord
of the index i
in the array.
int *p = &points[i].ycoord; /* Crea un puntero a points[i].ycoord */
The assembly result will be:
LEA ESI, [EBX + 8*EAX + 4] ; Carga solo la dirección de memoria.
In this case you did not want to assign the value of ycoord
in the index i
of your array, instead, you created a pointer and assigned it to ESI
.
Changing all that, and assuming that the index you're trying to access is 4
and that the address of array[0]
is zero, the code performs the following calculations:
LEA ESI, [0 + 8 * 4 + 4]
Dirección | Tamaño x Indice + Offset
base de variable necesitada.
It is worth mentioning that this example is valid for the code placed above, so it can change.