简体   繁体   English

动态变量的内存分配过程是怎样的?

[英]How does the process of memory allocation of dynamic variables?

When a function is called, a space in memory is reserved for local variables (formal parameters and those declared within the function's scope).当一个函数被调用时,内存中的空间是为局部变量(形式参数和那些在函数范围内声明的)保留的。 I understand that in ANSI C, because it is required that the variables are declared at the beginning of a block.我理解在 ANSI C 中,因为需要在块的开头声明变量。

However, in the case of the following C code compiled with GCC, will the z variable will have its space allocated at the beginning of the block or only when y is equal to 42 ?但是,在以下使用 GCC 编译的 C 代码的情况下, z变量将在块的开头分配空间还是仅当y等于42

void foo(int x) {
    int y;
    scanf("%d%*c", &y);
    if (y != 42)
        return;
    int z;
    return;
}

Is the behavior the same for other higher level languages such as Python and Ruby, with similar code?对于具有类似代码的其他高级语言(例如 Python 和 Ruby),行为是否相同?

This is typically implemented by reserving space on the stack for all variables that are declared in the method.这通常是通过在堆栈上为方法中声明的所有变量保留空间来实现的。 It would certainly be possible to do it dynamically, but that would require each "potential" variable to internally be represented as a pointer (since its address cannot be known in advance), and the overhead would almost certainly not be worth it.当然可以动态进行,但这需要每个“潜在”变量在内部表示为一个指针(因为它的地址不能提前知道),而且开销几乎肯定不值得。 If you really want "dynamic" variables, you can implement it yourself with pointers and dynamic memory allocation.如果你真的想要“动态”变量,你可以用指针和动态内存分配自己实现它。

Java and C# do the same thing: they reserve space for the total collection of local variables. Java 和 C# 做同样的事情:它们为局部变量的总集合保留空间。

I don't really know about Python or Ruby, but in these languages, there is no such thing as a primitive data type: all values are references and stored on the heap.我不太了解 Python 或 Ruby,但在这些语言中,没有原始数据类型这样的东西:所有值都是引用并存储在堆上。 As such, it is entirely possible that the storage space for the value referred to by a variable won't appear until the variable "declaration" is executed (although "declaration" isn't really a thing in dynamic languages; it's more of an assignment to a variable that happens do not exist yet).因此,在执行变量“声明”之前,变量引用的值的存储空间完全有可能不会出现(尽管“声明”在动态语言中并不是真正的东西;它更像是一个对发生的变量的赋值尚不存在)。 Note, though, that the variable itself also requires storage space (it's a pointer, after all) - however, the variables of dynamic languages are often implemented as hashmaps, so the variables themselves may also dynamically appear and disappear.但是请注意,变量本身也需要存储空间(毕竟它是一个指针)——但是,动态语言的变量通常被实现为哈希图,因此变量本身也可能动态地出现和消失。

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

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