-1

I have written a code for example

.global _start
.data
str:
    .long 0x1
.text
_start:
  mov  $1, %rax         # system call 1 is write
  mov  $0x21, %rdx
  mov  %rdx, 4(%rax)

  mov  $60, %rax        # system call 60 is exit
  xor  %rdi, %rdi       # we want return code 0
  syscall               # invoke operating system to exit

why do I receive a segmentation fault? When do I use the memory location? How do I use the memory location?

volkov
  • 117
  • 3
  • 13
  • 2
    Use _what_ memory location? Right now it looks like you're trying to write to address 5 (4+1), which is probably not mapped to your process. – Michael Mar 24 '13 at 12:10
  • What does it mean to "use" a memory location? – jalf Mar 24 '13 at 12:10
  • When do I use the memory location? I receive the segmentation fault probably I chose the bad example. – volkov Mar 24 '13 at 12:16
  • 1
    Your question doesn't make much sense. It is you to define when to use a memory location, why ask us? Also, what memory location do you mean by `the memory location`? Looks like you need to clarify your question. You might want someone help you with English if that's a problem. – Alexey Frunze Mar 24 '13 at 12:22
  • @Alexey Frunze %eax is register EAX; (%eax) is the memory location whose address is contained in the register EAX; 8(%eax) is the memory location whose address is the value of EAX plus 8. I write the code but it isn't working. I'm trying to understand why I get mistake segmentation fault. – volkov Mar 24 '13 at 12:28
  • 1
    But the only place where you access memory is `mov %rdx, 4(%rax)` and rax is 1, so you attempt to write 0x21 (as 8 bytes) into memory at address 5. Michael has already pointed out that 5 is unlikely to be a valid address. Why do you use 5? – Alexey Frunze Mar 24 '13 at 12:41
  • @Alexey Frunze because at manuals this part bad explained. how is address discover where to write? – volkov Mar 24 '13 at 13:00
  • 2
    Well, you typically define variables and then use their addresses or you receive valid addresses from somewhere else (e.g. from C's `malloc()`). You defined the `str` variable, its address is valid, you could use it. – Alexey Frunze Mar 24 '13 at 13:03

1 Answers1

1

You're trying to write the value in rdx to memory location 5. (rax+4, and rax was initialized to 1).

Are you running this program on a real computer or a simulator?

If you're running it on a computer, you cannot just write to arbitrary memory locations. The operating system allocates a certain amount of memory to a process, and if the process tries to access memory outside this range, this can cause a segmentation fault.

Its okay if you're running it on a simulator and there's no OS. If you want to write to memory, declare a variable in the data segment like this:

.data
myvar:
    .long 0x1
.text
_start:
  #....
  mov  %rdx, myvar
  #...
Neha Karanjkar
  • 3,390
  • 2
  • 29
  • 48