简体   繁体   English

为可变大小数组分配内存的机制

[英]Mechanism of allocating memory for variable size array

I am not able to understand how variable size array works , whether memory for it is allocated on stack or somewhere else and how information about its size is obtained. 我无法理解变量大小数组是如何工作的,无论是在堆栈上还是在其他地方分配内存,以及如何获取有关其大小的信息。

i tried the following code 我尝试了以下代码

#include<stdio.h>

int main()
{
    int n;
    scanf("%d",&n);

    int arr[n];

    printf("%d\n",sizeof(arr));

    return 0;
}

i mean i memory is allocted on stack ,then before running this function the stack frame is to be allocated and memory for local variables has to be allocated ,but the size of array is known after the function calls scanf(). 我的意思是我在堆栈上分配内存,然后在运行此函数之前,必须分配堆栈帧并且必须分配局部变量的内存,但是在函数调用scanf()之后,数组的大小是已知的。

In C++, this isn't (yet) allowed, although some compilers allow it as a non-standard extension. 在C ++中,虽然有些编译器允许将其作为非标准扩展,但尚未允许这样做。 Dynamically-sized arrays, similar to those in C, are due to be introduced in C++14. 动态大小的数组,类似于C中的数组,将在C ++ 14中引入。

How to implement this is up to the compiler writer, as long as the memory is allocated somewhere and freed automatically. 如何实现这一点取决于编译器编写器,只要内存在某处分配并自动释放即可。 This is typically done by extending the stack frame once the size is known. 这通常通过在已知大小时扩展堆栈帧来完成。 There may or may not be a check that the stack is large enough, so beware creating large arrays like this. 可能会或可能不会检查堆栈是否足够大,因此请注意创建这样的大型数组。

On most contemporary systems with memory protection and so on, you can just grow the stack. 在大多数具有内存保护等功能的现代系统中,您可以增加堆栈。 If accessing the grown stack causes accesses to memory which is actually outside the valid range of virtual memory for the process, the operating system will catch that and map some more memory your way. 如果访问增长的堆栈导致对内存的访问实际上超出了进程的有效虚拟内存范围,操作系统将捕获该内存并以您的方式映射更多内存。

So there's no problem in doing that "on the fly", and of course "allocating n bytes on the stack" is generally about as complex as "stackpointer -= n". 因此,“动态”执行此操作没有问题,当然“在堆栈上分配n个字节”通常与“stackpointer - = n”一样复杂。

There might be some additional complexity if the function has many exit paths, since they need to unwind the proper amount of stack depending on wether the variable-length array has been allocated or not, not sure how that is generally solved. 如果函数具有许多退出路径,则可能存在一些额外的复杂性,因为它们需要展开适当的堆栈量,这取决于是否已经分配了可变长度数组,不确定通常如何解决该问题。 That would be an easy code-reading exercise to find out. 这将是一个简单的代码阅读练习,以找出答案。

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

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