1

I am attempting to mimic the following C code in assembly:

int x = 12;
int *y = &x;
int z = *y;

I have the following:

mov rbp, rsp
sub rsp, 16

mov DWORD [rbp - 4], 12
lea eax, [rbp - 4]
mov DWORD [rbp - 8], eax
mov eax, DWORD [rbp - 8]
mov edi, DWORD [eax]

However, I receive a segmentation fault when calling the last line of assembly. Am I missing another layer of indirection?

sdasdadas
  • 23,917
  • 20
  • 63
  • 148
  • 4
    Don't truncate pointers to 32-bit. `lea eax, [rbp - 4]` - take the 64-bit stack address and truncate it to 32-bit. `mov edi, [eax]` override the address size to 32-bit, using the low half of RAX. RSP is a 64-bit register, and on normal OSes is outside the low 4GiB. – Peter Cordes Feb 19 '21 at 06:35
  • Thanks @PeterCordes that makes sense. I've fixed it by ensuring my pointers are the correct size and data type. – sdasdadas Feb 19 '21 at 06:37
  • 1
    Looking for a duplicate now; I'm sure this isn't new. That's why I answered in comments. – Peter Cordes Feb 19 '21 at 06:38
  • Does `mov edi, DWORD [eax]` make sense in a 64 bit environment, `eax` being a 32 bit value? – Jabberwocky Feb 19 '21 at 08:25
  • [What do the E and R prefixes stand for in the names of Intel 32-bit and 64-bit registers?](https://stackoverflow.com/q/43933379) is related if you didn't realize that EAX is a 32-bit register. Didn't manage to turn up an exact duplicate with google. – Peter Cordes Feb 19 '21 at 08:29

0 Answers0