Search code examples
assemblyx86-64attpointer-arithmetic

Assembly - lea and arithmetic


Context:

  • Assembly
  • gas
  • x86_64

My assembly is a bit rusty and I try to make it good again.

The C code showing the intent:

void ask_me(int * data){

    (*data)++;

}

It is deliberately stupid, but fits the context.

My working assembly :

_ask_me:
   addq $1, (%rdi)
   ret

Question:

I would like to use the lea instruction, as a training. But I couldn't make it work:

_ask_me:
    leaq 1(%rdi), %rdi

    ret

Worst:

_ask_me:
    movq (%rdi), %rcx
    leaq 1(%rcx), %rdi

    ret

Could you remind me how to do it ?

Thanks


Solution

  • The original assembly reads and writes from/to memory. That is:

    addq $1, (%rdi) 
    

    performs the operation:

    *(rdi) += 1
    

    You cannot achieve the same thing with LEA, because LEA stores the result in a register, not in memory. So you can use it do to rdi += 1 (as in your first attempt), but not *(rdi) += 1.