I am currently following an introductory course in microelectronics and assembly programming in Uni. At the beginning of every function, I'm saving the caller's base pointer by pushing it onto the stack. Given the following function, I get an error:
.globl my_func
.globl _my_func
my_func:
_my_func:
pushl %ebp
movl %esp,%ebp
movl 4(%esp),%ebx
subl $1,%ebx
movl %ebx,%eax
ret
0xbffff8a8: aam $-0x8 <-EXC_BAD_ACCESS (code=2, address=0xbffff8a8)
I've figured out this is a memory exception, I just don't understand why it's being thrown. When I skip the first two instructions in the function (the base pointer saving), the function runs well. And before you point it out -- yes, I know the function is pointless and slow, I'm just trying to learn how the instructions work, and how to use the stack and registers.
I'm assembling it for IA32 on an Intel Mac with OSX10.9 using LLVM5.1
You need to reset the stack pointer at the end of the function, either explicitly or by popping a register to match what you pushed at the start of the function, otherwise when you return it will be to an invalid address:
popl %ebp ; restore stack pointer to its original value
ret
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With