简体   繁体   中英

Why I this address is being changed after initialization in main function? (C)

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.

这里的 top 属性很好地指向了数组的开头

返回后指针保持不变,但数组的第一个元素的地址发生了变化

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM