Search code examples
assemblyx86segmentation-fault

falling in segmentation fault in x86 assembly


I am trying to print each charactere after a comma with printf, but it gives me segmentation fault

global main

extern printf

section .data
        num db "%d",0
        array db 2,4,3
        arrlen equ $ - array

section .text
main:
        mov ecx, 0

mainloop:
        cmp ecx, arrlen
        je exit

        movzx ebx, byte [array + ecx]
        push ebx
        push num
        call printf

        add esp, 8

        inc ecx
        jmp mainloop

exit:
        mov eax, 1
        xor ebx, ebx
        int 0x80

I tried even to use chatGPT xd


Solution

  • ECX is not a call-preserved register. printf probably modifies it so your ECX-based loop runs for too long, hence addressing memory beyond the array.
    Try using EBX that is a call-preserved register:

    main:
            xor   ebx, ebx
            jmp   beginloop
    mainloop:
            movzx eax, byte [array + ebx]
            push  eax
            push  num
            call  printf
            add   esp, 8
            inc   ebx
    beginloop:
            cmp   ebx, arrlen
            jb    mainloop
    exit:
            mov   eax, 1
            xor   ebx, ebx
            int   0x80