0

I'm trying to use scanf to scan for two integers but everything I try seems to result segmentation fault for the second integer, could you please assist me?

.data
.align  8
.section    .rodata
scan_int:       .string "%d"
.text

pushq   %rbp
movq    %rsp,  %rbp
pushq   %rdi
pushq   %rdx                   # Save calle registers before calling an outer function.
subq    $8,   %rsp              # allocate 8 bytes for scanf. - keep stack line asignment
lea     scan_int(%rip), %rdi    # efficient format loading to rdi.
xorq    %rax,        %rax       # rax = 0, for scanf function.
leaq    (%rsp),      %rsi       # set storage to local variable
call    scanf

subq    $8,   %rsp              # allocate 8 bytes for scanf. - keep stack line asignment
lea     scan_int(%rip), %rdi    # efficient format loading to rdi.
xorq    %rax,        %rax       # rax = 0, for scanf function.
leaq    (%rsp),      %rsi       # set storage to local variable
call    scanf

when trying to debug using gdb and nexti command on the scanf line I get the following error.

Program received signal SIGSEGV, Segmentation fault. 0x00007ffff7e44c05 in __vfscanf_internal (s=0x7ffff7fa99a0 <IO_2_1_stdin>, format=0x4020ba "%d", argptr=argptr@entry=0x7fffffffdbb8, mode_flags=mode_flags@entry=0) at vfscanf-internal.c:339 339 vfscanf-internal.c: No such file or directory. (gdb) Program received signal SIGSEGV, Segmentation fault.

I would love to know what am I doing wrong with the scanf and also know if debugging scanf with gdb is possible.

Thank you.

  • One thing I notice is that you misalign the stack. Try to subtract only 8 bytes for scanf to preserve stack alignment. It is difficult to provide more help because you have not supplied an [mcve]. – fuz Nov 19 '21 at 09:22
  • Thank you for the quick answer! you answer fixed my problem for the first scanf, but then for the upcoming one getting same error, could you advice me what steps should I take to fix it? – Itay Etelis Nov 19 '21 at 09:31
  • Please don't do this thing were you expand your question by a new one once you get an answer. Instead, post a new question. But anyway, the problem is the same: you misalign the stack. The stack pointer must always be a multiple of 16 bytes. By subtracting just 8 from it before the second `scanf` call, you once again misalign it. – fuz Nov 19 '21 at 09:34

0 Answers0