dmlittle
dmlittle

Reputation: 999

x86-64 Assembly Based Indexed Addressing & Segfaults

I'm having trouble with the following assembly code.

.section .rodata
.globl main
main:
enter $(8*10),$0

mov $10, %rax

mov -48(%rbp), %r10
mov $1, %r11
mov %rax, (%r10, %r11, 8)

main_return:
leave
ret

Here's what I think, the code I wrote is doing, but I might be wrong.

  1. Create a new stack frame with 10 (64-bit) locations I can potentially use.
  2. Load the immediate value of 10 into the %rax register
  3. Store the value in %rax into %r10+(%r11)*8 (in other words -40(%rbp))

For some reason, the code produces a segmentation fault when compiled and run using gcc. However, when the immediate value of $0, or $2 are loaded, the segmentation fault disappears. I'm trying to understand why this is the case.

The command I'm using to compile the assembly code is: gcc code.s -o code and I'm running the program by simply executing ./code.

Upvotes: 2

Views: 123

Answers (1)

Ross Ridge
Ross Ridge

Reputation: 39551

The instruction mov -48(%rbp), %r10 moves the value stored at -48(%rbp) into R10. This value can be anything since its taken from part of of the function's stack allocation (allocated with the ENTER instruction) and you never initialized it.

If you want to load the address of -48(%rbp) into a register you should use the LEA instruction:

lea -48(%rbp), %r10

You can also fold it into the instruction where you store RAX:

mov %rax, -48(%rbp, %r11, 8)

Upvotes: 2

Related Questions