I'm making a basic assembly subtraction function and printing the result to the console. Here's the code I think SHOULD work:
(compiled with as output.s
, ld a.out -e _start -o output
)
.bss
output:
.int
.text
.global _start
_start:
movl $9, %eax
movl %eax, %ebx
movl $8, %eax
subl %eax, %ebx
movl %ebx, (output)
# ASCII for digits is 0x30 greater than digit value
addl $0x30, output
movl $2, %edx # write 2 bytes (need 1 for null?)
movl $output, %ecx # output
movl $1, %ebx # write to stdin
movl $4, %eax # syscall number for write
int $0x80 # invoke syscall
# CR
movl $2, %edx
movl $13, (output)
movl $output, %ecx
movl $1, %ebx
movl $4, %eax
int $0x80
# LF
movl $2, %edx
movl $10, (output)
movl $output, %ecx
movl $1, %ebx
movl $4, %eax
int $0x80
# exit
movl $0, %ebx
movl $1, %eax
int $0x80
However, this program segfaults. I found that if I add a trivial .data section at the end:
.data
pingle:
.int 666
it works fine. Why do I need the .data segment? Am I overflowing one of the segments when I write 2 bytes each time? Or is overwriting output
several times doing this?
Any ideas are much appreciated!