0

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.

Here the top property is well pointed to the start of the array

After the return the pointer remains the same but the address of the first element of the array has changed

Gonzalo
  • 185
  • 1
  • 12

1 Answers1

0

The problem was VM was declared in the local scope. Allocating VM in the heap solved it.

Gonzalo
  • 185
  • 1
  • 12