Search code examples
arraysassemblygnu-assembleratt

segmentation fault with .text .data and main (main in .data section)


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?


Solution

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

    It leads to a segmentation fault on systems that doesn't allow to execute code in the .data section. (Most modern systems map .data with read + write but not exec permission.)

    Program code should be in the .text section. (Read + exec)

    Surprisingly, on GNU/Linux systems, hand-written asm often results in an executable .data unless you're careful to avoid that, so this is often not the real problem: See Why data and stack segments are executable? But putting code in .text where it belongs can make some debugging tools work better.


    Also you need to ret from main or call exit (or make an _exit system call) so execution doesn't fall off the end of main into whatever bytes come next. See What happens if there is no exit system call in an assembly program?