Assembly homework assignment error

0

I have the two following files: task2.s:

section .data
answer1: DB "the number is divisible by 3",10,0
answer2: DB  "the number is not divisible by 3",10,0
sum_even: DD 0
sum_odd: DD 0
res: DD 0
number: DD 0
stack: DD 0
section .text
global isDivisibleBy3
extern check
extern printf


isDivisibleBy3:
push    ebp             ; Save caller state
mov     ebp, esp
mov     [stack],esp     ; save the pointer the to stack head pointer when called to function
pushad                  ; Save some more caller state

mov ecx, [ebp+8]    ; Copy function args to registers ecx    
mov [number],ecx
_division:
mov edx, 0     
mov eax, [number]
mov ebx, 2
div ebx
mov [number],eax
    add [sum_even],edx
cmp byte [number],0
jz _return
mov edx, 0     
mov eax, [number]
mov ebx, 2
div ebx
mov [number],eax
    add [sum_odd],edx
cmp byte [number],0
jnz _division

_return:
mov  edx,[sum_odd]
mov  eax,[sum_even]
push edx
push eax
and byte [sum_even],0
and byte [sum_odd],0
add ebp,4

call check


mov [res],eax

cmp byte[res],1
jz _return1
cmp byte[res],-1
jz _return2

ret                     ; Back to caller

_return1:
push answer1
call printf


popad                   ; Restore caller state (registers)
mov     esp,[stack]
pop     ebp             ; Restore caller state
ret                     ; Back to caller

_return2:
push answer2
call printf

popad                   ; Restore caller state (registers)
mov     esp,[stack]
pop     ebp             ; Restore caller state
ret                     ; Back to caller

and the file main2.c:

#include <stdio.h>
#include <string.h>
#include<stdlib.h>
#define BUFFER_SIZE(1024)

extern void isDivisibleBy3(int x);

int main(int argc, char** argv)
{
  char buf[BUFFER_SIZE];    
  printf("Enter string: ");
  fflush(stdout);
  fgets(buf, BUFFER_SIZE, stdin);
  int number=atoi(buf);
  printf("Got Number: %d\n", number);
  isDivisibleBy3(number);
  return 0;
}

int check(int evenBits, int oddBits){
  int res=abs(evenBits-oddBits);
  switch (res){
    case 0:{return 1;}
    case 1:{return -1;}
    case 2:{return -1;}
    default: {isDivisibleBy3(res);}
  }
  return 0;
}

I'm compiling the file and run them on Linux x86 when i insert in runtime small number like 1234 the program work well and return the correct value with no errors but if i will insert the number 976431 in runtime i will get the correct answer but with

the number is divisible by 3

Program received signal SIGSEGV, Segmentation fault.
0x00000005 in ?? ()
(gdb) where
#0  0x00000005 in ?? ()
#1  0x00000008 in ?? ()
#2  0x00000000 in ?? ()

and i think 5 and 8 on the stack are sum_even and sum_odd

i don't no how to overcome the error on stack or why this is happening with long numbers.

assembly
x86
asked on Stack Overflow Apr 3, 2014 by user3136572 • edited Mar 6, 2017 by Paul R

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0