0

I have this assembly code which gives me a segmentation fault and I do not know why.

        .global _main
_main:
    pushq   %rbp
    movq    %rsp, %rbp
    subq    $16, %rsp
    movl    $0, -4(%rbp)

    callq _getint
    pushq %rax

    callq _getint
    pushq %rax

    leaq    str(%rip), %rdi
    popq    %rsi
    
    movb    $0, %al
    callq   _printf

    leaq    str(%rip), %rdi
    popq    %rsi
    
    movb    $0, %al
    callq   _printf

    xorl    %eax, %eax
    addq    $16, %rsp
    popq    %rbp
    retq

The _getint function is the assembly you would get with gcc if you compiled:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

long getint()
{
    char *end;
    char buf[100];

    long res;

    do {
        if (!fgets(buf, sizeof(buf), stdin)) break;

        buf[strcspn(buf, "\n")] = '\0';

        res = strtol(buf, &end, 10);
    } while (end != buf + strlen(buf));

    return res;
}

I would really appricieate help on this topic.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
  • Stack alignment, maybe? You have proper 16-byte stack alignment after `subq $16, %rsp`, but every odd-numbered push/pop thereafter misaligns it, and you must not make a call to a C function when it is misaligned. – Nate Eldredge May 12 '22 at 02:50
  • See https://stackoverflow.com/questions/49391001/why-does-the-x86-64-amd64-system-v-abi-mandate-a-16-byte-stack-alignment/49397524#49397524 – Nate Eldredge May 12 '22 at 02:55

0 Answers0