c - Segmentation Fault when getting the max of three numbers in Assembly x86 -
i trying max of 3 numbers using c call method in assembly 32 bit @ & t. when program runs, segmentation fault(core dumped) error , cannot figure out why. input has been mix of positive/negative numbers , 1,2,3, both same error result.
assembly
# %eax - first parameter # %ecx - second parameter # %edx - third parameter .code32 .file "maxofthree.s" .text .global maxofthree .type maxofthree @function maxofthree: pushl %ebp # old ebp movl %esp, %ebp # skip on movl 8(%ebp), %eax # grab first value movl 12(%ebp), %ecx # grab second value movl 16(%ebp), %edx # grab third value #test first cmpl %ecx, %eax # compare first , second jl firstsmaller # first smaller second, exit if cmpl %edx, %eax # compare first , third jl firstsmaller # first smaller third, exit if leave # reset stack pointer , pop old base pointer ret # return since first > second , first > third firstsmaller: # first smaller second or third, resume comparisons #test second , third against each other cmpl %edx, %ecx # compare second , third jg secondgreatest # second greatest, jump end movl %eax, %edx # third greatest, move third eax leave # reset stack pointer , pop old base pointer ret # return third secondgreatest: # second > third movl %ecx, %eax #move second eax leave # reset stack pointer , pop old base pointer ret # return second
c code
#include <stdio.h> #include <inttypes.h> long int maxofthree(long int, long int, long int); int main(int argc, char *argv[]) { if (argc != 4) { printf("missing command line arguments. instructions to" " execute program:- .\a.out <num1> <num2> <num3>"); return 0; } long int x = atoi(argv[1]); long int y = atoi(argv[2]); long int z = atoi(argv[3]); printf("%ld\n", maxofthree(x, y, z)); // todo change (x, y, z) }
the code causing segmentation fault because trying jump invalid return address when ret
instruction executed. happens 3 different ret
instructions.
the reason why occurring because don't pop old base pointer before returning. small change code remove fault. change each ret
instruction to:
leave ret
the leave
instruction following:
movl %ebp, %esp popl %ebp
which reset stack pointer , pop old base pointer saved.
also, comparisons not doing specified in comments. when do:
cmp %eax, %edx jl firstsmaller
the jump happen when %edx
smaller %eax
. want code be
cmpl %edx, %eax jl firstsmaller
which jump when %eax
smaller %edx
, specified in comment.
reference this page details on cmp
instruction in at&t/gas syntax.
Comments
Post a Comment