下面的虚拟机在我的堆栈增量指令中出现段错误,该指令从 bin 指针获取堆栈偏移量并将其加一。如果我使用值 -1 这可以正常工作,但是当我-1
通过bp[1]
偏移量访问时它会崩溃。这对我来说真的没有意义,我做错了什么?
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
typedef enum {PUSH,STACKINC,EXIT} opCodes;
char * opCode[] = {"Push","Stack Increment","Exit"};
typedef struct VirtualMachine
{
uint32_t * sp; /* Stack Pointer */
uint32_t * bp; /* Bin Pointer */
uint32_t stack[100]; /* VM stack */
} VM;
void processVM(VM * vm)
{
uint32_t * bp = vm->bp;
uint32_t * sp = vm->sp;
printf("OP: %s\n",opCode[bp[0]]);
switch (bp[0])
{
case PUSH: sp[0] = bp[1]; sp++; bp+=2; break;
case STACKINC: sp[bp[1]]++; bp+=2; break;
}
vm->bp = bp;
vm->sp = sp;
/* Set out stack and bin pointers back */
}
int main()
{
uint32_t binFile[] = {PUSH,1,PUSH,2,PUSH,3,STACKINC,-1,EXIT};
VM myVM;
myVM.bp = binFile;
myVM.sp = myVM.stack;
while(myVM.bp[0] != EXIT)
{
processVM(&myVM);
usleep(200000);
}
printf("VM done executing\n");
}