简体   繁体   English

为什么数组大小可访问但动态分配的 memory 大小在运行时无法访问?

[英]Why is array size accessible but dynamically allocated memory size is inaccessible at runtime?

If I declare an array double x[n] where n is either a constant or an int variable, I can get it's size during runtime.如果我声明一个数组double x[n] ,其中 n 是常量或 int 变量,我可以在运行时获取它的大小。 But if I allocate memory using malloc this does not happen.但是,如果我使用malloc分配 memory 这不会发生。 Is this because of stack vs heap memory allocation?这是因为堆栈与堆 memory 分配吗? If so how are array sizes for global variables determined and why can't I declare variable length arrays as global variables?如果是这样,如何确定全局变量的数组大小,为什么我不能将可变长度 arrays 声明为全局变量? and how does deallocation work since you need to know how much memory to free?以及释放如何工作,因为您需要知道要释放多少 memory?

The answer to basically all of your questions is that the memory allocator privately knows how much memory it allocated, but not the type of your object.基本上所有问题的答案是 memory 分配器私下知道它分配了多少 memory,但不知道 object 的类型。 In fact, it might only know how many blocks of some fixed size it allocated, not necessarily the same as the number of bytes requested.事实上,它可能只知道它分配了多少固定大小的块,不一定与请求的字节数相同。 Therefore it does not know how many elements that "array" contains, or even if it's being used as an array at all.因此它不知道“数组”包含多少元素,或者根本不知道它是否被用作数组。

You are expected to keep track of usage-specific information yourself if you need it.如果需要,您应该自己跟踪使用特定信息。 You simply request however many bytes you need and then use that memory however you choose.您只需请求所需的字节数,然后使用 memory 即可。 It is not the allocator's responsibility to assist you with this, which gives you full flexibility to do whatever you want.分配器不负责协助您完成此操作,这使您可以完全灵活地做任何您想做的事情。

The array x in your example has a known type and size at compile time, or can be inferred at runtime.您示例中的数组x在编译时具有已知的类型和大小,或者可以在运行时推断。 In other words, the compiler knows that it should push some number of bytes onto the stack based on the size value and use them as an array of the defined type.换句话说,编译器知道它应该根据大小值将一些字节数压入堆栈,并将它们用作定义类型的数组。

It makes less sense to have VLAs at global scope, since the whole point of the VLA is that it is allocated based on the variable size when entering a block scope.在全局 scope 中使用 VLA 就没那么有意义了,因为 VLA 的全部意义在于,当进入块 scope 时,它是根据可变大小分配的。 The global scope is only entered once when your program is initialized.全局 scope 仅在程序初始化时输入一次。

During translation, the compiler keeps track of all variable definitions and their sizes.在翻译期间,编译器会跟踪所有变量定义及其大小。 Except for VLAs, the sizeof operator is evaluated at compile time, not runtime.除了 VLA, sizeof运算符在编译时计算,而不是在运行时计算。 How the sizes of VLAs are tracked is up to the individual implementation.如何跟踪 VLA 的大小取决于各个实现。

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

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