简体   繁体   English

为什么我这个地址在主 function 初始化后被更改? (C)

[英]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.我是 C 的新手,我正在处理的项目遇到一些问题。

In vm.h在 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在 vm.c

void resetStack(Stack* stack) {
    stack->top = stack->values
}

VM initVM() {
    VM vm;
    resetStack(&vm.stack);
    return VM;
}

In main.c在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.在我初始化 vm 之后,vm.stack.top 指向 vm.stack.values[0] (我不知道为什么用垃圾值而不是零填充),但是无论如何,一条指令之后,vm。 stack.top 已更改并开始指向其他内容,或者有时 vm.stack.values[0] 的地址更改为另一个。

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

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

The problem was VM was declared in the local scope.问题是在本地 scope 中声明了 VM。 Allocating VM in the heap solved it.在堆中分配 VM 解决了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 回到C中的main时,为什么传递给函数的FILE指针改变了? - Why FILE pointer after being passed to a function changes when back in main in C? 为什么在ret地址溢出后,作为函数参数给出的字符串的地址发生了变化? - Why the address of a string given as argument to a function changed after overflowing the ret address? 如果在 main() 之后定义的函数中没有返回值,为什么 C 中不需要函数原型? - Why is a function prototype not needed in C if there is no return in a function defined after main()? C / C ++中函数main()的地址 - Address of function main() in C/C++ 结构的初始化函数(即“构造函数”),为什么变量未正确初始化? - Initialization function (i.e. “constructor”) for struct, why are variables not being initialized properly? C - 函数无意中更改了字符串 - C - String being changed by function unintentionally C - 如何保护变量在函数中的某个点之后不会被意外更改 - C - how to protect a a variable from being accidentally changed after a certain point in the function 为什么 main() 后面有 function 定义? - Why there are function definitions after the main()? 为什么我运行代码前后function地址不一样? - Why the function address is different before and after I run the code? 为什么除main以外的函数中的数组初始化是临时的? - why does array initialization in function other than main is temporary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM