segmentation fault when assigning value of an array to eax (AT&T syntax)

点点圈 提交于 2020-01-23 10:20:08

问题


I'm just trying to load the value of myarray[0] to eax:

        .text
        .data

        # define an array of 3 words
array_words:     .word 1, 2, 3

        .globl main

main:
        # assign array_words[0] to eax
        mov $0, %edi
        lea array_words(,%edi,4), %eax

But when I run this, I keep getting seg fault. Could someone please point out what I did wrong here?


回答1:


It seems the label main is in the .data section.

It should lead to segmentation fault if the system doesn't allow to execute codes in .data section.

Program code should be in the .text section.




回答2:


You need to properly terminate your program, e.g. on Linux x86_64 by calling the sys_exit system call:

...
main:
     # assign array_words[0] to eax
     mov $0, %edi
     lea array_words(,%edi,4), %eax

     mov $60, %rax       # System-call "sys_exit"
     mov $0, %rdi        # exit code 0
     syscall

Otherwise program execution continues with the memory contents following your last instruction, which are most likely in all cases invalid instructions (or even invalid memory locations).



来源:https://stackoverflow.com/questions/34350582/segmentation-fault-when-assigning-value-of-an-array-to-eax-att-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!