Reputation: 837
So, I am trying to use the scanf
function in 32bit ATT assembly and keep getting segmentation faults, despite using pretty much the same code as the example shown in Computer Systems: A Programmer's Perspective
and the assembly generated from my own simple C input program. I have no idea what it is I am doing wrong and would appreciate some help in figuring it out.
My test assembly code(which segfaults):
.data
.align 4
fmt: .string "%d"
str: .string "Input a number: "
.text
.global main
.type main, @function
main:
pushl %ebp
movl %esp, %ebp
subl $40, %esp
movl $str, (%esp)
call printf
leal 36(%esp), %eax
movl %eax, 4(%esp)
movl $fmt, (%esp)
call scanf
pushl -4(%ebp)
call printf
movl %ebp, %esp
popl %ebp
ret
The C code and it's assembly:
C:
#include <stdio.h>
int main()
{
int i, j;
printf("%s\n","Enter 2 numbers:");
scanf("%d %d",&i,&j);
printf("i = %d and j = %d\n",i,j);
return 0;
}
assembly:
.file "scan.c"
.section .rodata
.LC0:
.string "Enter 2 numbers:"
.LC1:
.string "%d %d"
.LC2:
.string "i = %d and j = %d\n"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp
.cfi_def_cfa_register 5
andl $-16, %esp
subl $32, %esp
movl $.LC0, (%esp)
call puts
leal 28(%esp), %eax
movl %eax, 8(%esp)
leal 24(%esp), %eax
movl %eax, 4(%esp)
movl $.LC1, (%esp)
call __isoc99_scanf
movl 28(%esp), %edx
movl 24(%esp), %eax
movl %edx, 8(%esp)
movl %eax, 4(%esp)
movl $.LC2, (%esp)
call printf
movl $0, %eax
leave
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4"
.section .note.GNU-stack,"",@progbits
The example in the book(in a cropped screenshot):
Upvotes: 2
Views: 2461
Reputation: 58772
You simply forgot the format string for the printf
.
You effectively do printf(i)
instead of printf("%d", i)
.
Thus change:
pushl -4(%ebp)
call printf
To:
pushl -4(%ebp)
pushl $fmt
call printf
PS: learn to use a debugger.
Upvotes: 5