I have a program that is supposed to either add or subtract two hardcoded numbers based on user input 0
or not 0
. I get memory access violation error i
cmp %esp, '0'
is wrong, because it tries to compare the value of %esp
to the value in memory at address '0'
. At&t syntax uses reversed operands, and it needs a $
prefix for immediates. But you already know this, I guess you were just a little careless. The correct instruction is cmpb $'0', (%esp)
to compare the byte in memory at address %esp
to the ascii code of 0
.
Furthermore, you allocated 4 bytes from the stack, but you never free that. When you eventually hit a ret
it will use your local variable as return address which is of course a bad thing :) A nice trick is to use lea 4(%esp), %esp
to free it without affecting the flags, so you can do this between the cmp
and the jz
. If you like less tricky stuff, you can of course just pop the input into a register and use that in the comparison, such as:
pop %eax
cmp $'0', %al
PS: Learn to use a debugger. That would have pointed you directly at the instruction, and then you probably could have figured out the problem yourself.