I'm new to C and I'm facing some problems with a project I am working on.
In vm.h
#define STACK_MAX 256
typedef double Value;
typedef struct {
Value values[STACK_MAX];
Value* top;
}
typedef struct {
Chunk* chunk;
uint8_t* ip; // Instruction pointer
Stack stack;
} VM;
VM initVm();
void resetStack(Stack* stack);
In vm.c
void resetStack(Stack* stack) {
stack->top = stack->values
}
VM initVM() {
VM vm;
resetStack(&vm.stack);
return VM;
}
In main.c
int main() {
VM vm = initVM();
...
}
Ok, here's the problem. After I initialize vm, vm.stack.top is pointing to vm.stack.values[0] (which I don't know why is filled with garbage values instead of zeroes), but one instruction later, no matter what, vm.stack.top is changed and starts pointing something else or sometimes the address of the vm.stack.values[0] is changed to another.
The problem was VM was declared in the local scope. Allocating VM in the heap solved it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.