装配作业分配错误

时间:2014-04-03 10:24:09

标签: assembly x86

我有以下两个文件: 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

和文件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;
}

我正在编译该文件并在Linux x86上运行它们 当我在运行时插入小数字,如1234 程序运行良好,返回正确的值,没有错误 但如果我将在运行时插入数字976431我会得到正确的答案,但

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 ?? ()

我认为筹码中的5和8是 sum_even sum_odd

我不知道怎么克服堆栈上的错误或为什么会发生长数字。

0 个答案:

没有答案