创建堆栈VM时的分割故障



我正在尝试创建一个VM,该VM现在可以运行简单的内容。但是,经过编译后,我尝试运行它,但有一个细分故障。有4个文件:stack-vm.hstack-vm.cppmain.cppmakefile

stack-vm.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

stack-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;
}

makefile:

        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++)

是不正确的,应该是我,而不是1。

此外,储备还设定了容量,而不是矢量的大小。您应该使用调节大小。

相关内容

  • 没有找到相关文章

最新更新