gpt4 book ai didi

c++ - 创建 Stack VM 时出现段错误

转载 作者:行者123 更新时间:2023-11-28 04:22:58 24 4
gpt4 key购买 nike

我正在尝试创建一个 VM,它现在可以运行简单的东西。但是,编译后,我尝试运行它但出现了段错误。有 4 个文件:stack-vm.hstack-vm.cppmain.cppmakefile .

堆栈虚拟机.h :

#ifndef STACK_VM_H
#define STACK_VM_H

#include <iostream>
#include <vector>

//type definitions
typedef int32_t i32;

class StackVM {

private:
i32 pc = 100; // program counter
i32 sp = 0; // stack pointer
std::vector<i32> memory;
i32 typ = 0;
i32 dat = 0;
i32 running = 1;

i32 getType(i32 instruction);
i32 getData(i32 instruction);
void fetch();
void decode();
void execute();
void doPrimitive();

public:
StackVM();
void run();
void loadProgram(std::vector<i32> prog);

};

#endif

堆栈-vm.cpp :

    #include "stack-vm.h"

StackVM::StackVM() {
memory.reserve(1000000);
}

i32 StackVM::getType(i32 instruction) {
i32 type = 0xc0000000;
type = (type & instruction) >> 30;
return type;
}

i32 StackVM::getData(i32 instruction) {
i32 data = 0x3fffffff;
data = data & instruction;
return data;
}
void StackVM::fetch() {
pc++;
}

void StackVM::decode() {
typ = getType(memory[pc]);
dat = getData(memory[pc]);
}

void StackVM::execute() {
if (typ == 0 || typ == 2) {
sp++;
memory[sp] = dat;
} else {
doPrimitive();
}
}

void StackVM::doPrimitive() {
switch (dat) {
case 0: // halt
std::cout << "halt" << std::endl;
running = 0;
break;

case 1: // add
std::cout << "add " << memory[sp - 1] << " " << memory[sp] << std::endl;
memory[sp - 1] = memory[sp - 1] + memory[sp];
break;
}
}

void StackVM::run() {
pc -= 1;
while (running) {
fetch();
decode();
execute();
std::cout << "tos: " << memory[sp] << std::endl;
}
}

void StackVM::loadProgram(std::vector<i32> prog) {
for (i32 i = 0; 1 < prog.size(); i++) {
memory[pc + i] = prog[i];
}
}

main.cpp :

    #include "stack-vm.h"

int main(int argc, char* argv[]) {
StackVM vm;
std::vector<i32> prog{3, 4, 0x40000001, 0x40000000};
vm.loadProgram(prog);

return 0;
}

生成文件:

        CFLAGS=-std=c++11

all: stack-vm

stack-vm: stack-vm.o main.o
$(CXX) $(CFLAGS) stack-vm.o main.o -o stack-vm

main.o: main.cpp
$(CXX) $(CFLAGS) -c main.cpp

stack-vm.o: stack-vm.h stack-vm.cpp
$(CXX) $(CFLAGS) -c stack-vm.cpp

clean:
rm -f *.o stack-vm

感谢您的回答。

最佳答案

行:

for (i32 i = 0; 1 < prog.size(); i++)

不正确,应该是i,不是1。

此外,reserve 设置的是容量,而不是 vector 的大小。你应该使用调整大小。

关于c++ - 创建 Stack VM 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55027310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com