问题描述
我已经编写了Collatz猜想的x86实现,该实现接受一个int和大量的运行,然后使用Collatz猜想将int减少为一个,并返回这样做的迭代次数,但是我当我尝试使用我的cpp测试文件运行它时,收到了一个奇怪的,没有清晰来源的细分错误
我的x86代码是
global threexplusone
section .text
threexplusone:
push rbp ; load arg register
mov rbp,rsp ; move stack pointer to arg
mov rax,[rbp+8] ; input arg to rax
mov rcx,rax ; save arg in rcx
cmp rax,1 ; x == 1 ? Base Case
je baseCase
xor rdx,rdx
mov rbx,2
idiv rbx
cmp rdx,0 ; rax % 2 == 0 ? recurse : odd
je recurse
jmp odd
odd:
mov rax,rcx ; restores arg
lea rax,[3*rax+1] ; collatz math
jmp recurse
recurse:
push rax
call threexplusone
add rax,1 ; numRuns++
jmp end
baseCase:
mov rax,0 ; save rax to prevent segfault
end:
mov rsp,rbp
pop rbp
ret
我的cpp测试是:
#include <iostream>
#include "timer.h"
#include <cstdlib>
#include <string>
using namespace std;
extern "C" int threexplusone(int);
int main() {
int x,n,firstRun;
timer t1;
cout<<"Enter the number to test collatify"<<endl;
cin>>x;
cout<<"Enter the number of runs"<<endl;
cin>>n;
t1.start();
for(int i=0;i<n;i++) {
threexplusone(x);
}
t1.stop();
firstRun=threexplusone(x);
double mean = (t1.getTime()*1000)/n;
cout<<"Number of iterations: "<<firstRun<<endl;
cout<<"Mean runtime: "<<mean<<"ms"<<endl;
return 0;
}
我肯定知道计时器的实现工作正常,但是我对可能导致分段错误的原因感到困惑。我已经尝试了一些方法,例如在使用它们之前对某些变量进行了异或运算或使用imul而不是lea,但是到目前为止,没有任何问题可以解决此问题。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)