Introduction
I'm following "ProgrammingGroundUp" book. and I've followed the example of creating a function to raise the power of two numbers and adding them. "2^3 + 5^2". However when I go to compile the code, and then run the program. I receive a segmentation fault.
From my understanding a segmentation fault occurs when a program attempts to do an illegal read or write from a memory location. I think it could be occurring inside the function itself, however confused of where the segmentation fault has occurred.
Source Code - power.s
#purpose illustrate how functions work. Program will compute 2^3 + 5^2
#using registers so nothing in data section
.section .data
.section .text
.globl _start
_start:
pushl $3 #push 2nd arg on stack
pushl $2 #push 1st arg on stack
call power
addl 8,%esp #move stack pointer back
pushl %eax #push result to top of stack
pushl $2 #push 2nd arg on stack
pushl $5 #push 1st arg on stack
call power
addl 8,%esp #move stack pointer back
popl %ebx #put function1 result into ebx reg
addl %eax , %ebx #add return result of function2 + function1 result
movl $1 , %eax #exit system call
int $0x80
#PURPOSE: power function
#REGISTERS: %ebx - holds base number ; %ecx - holds power; -4(%ebp) -holds current result ;%eax temp storage
.type power,@function
power:
pushl %ebp #save state of base pointer
movl %esp,%ebp #make stack pointer the base pointer
subl $4,%esp #room for local storage
movl 8(%ebp),%ebx #1st arg initialized,
movl 12(%ebp),%ecx #2nd arg initialized,
movl %ebx , -4(%ebp) #store current result
power_loop_start:
cmpl $1,%ecx #if ^1 then jump to end_power & exit
je end_power
movl -4(%ebp),%eax #store current result
imull %ebx,%eax #multiply
movl %eax,-4(%ebp) #store result
decl %ecx #decrement ecx
jmp power_loop_start #loop
end_power: #return
movl -4(%ebp) , %eax #move result in eax for return
movl %ebp , %esp #reset the stack pointer
popl %ebp #reset base pointer to original position
ret #return
Compiling
as --32 power.s -o power.o
ld -m elf_i386 power.o -o power
./power
Segmentation fault
Summary
Segmentation fault occurring in code, Not sure where is exactly, very new to assembly, tried to explain as best I can. BTW used the "--32" as the code is 32bit and I'm on a 64bit machine.
*Also if my question doesn't meet stack overflow standards please let me know so I can improve.