下面的虚拟机正在堆栈增量指令处分段,该指令从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");
}
最佳答案
所有变量都是无符号的。即使你存储-1,当你读回来的时候你也会得到4294967295。
关于c - Mico C虚拟机分段故障,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10862622/