什么时候将内存分配给C中的局部变量 [英] When is memory allocated to local variables in C
问题描述
局部变量也称为自动变量,应该在运行时在访问函数时分配内存.
As local variables are also called automatic variables, and are supposed to be allocated memory at run time, when function is accessed.
int main(){
int a; // declaration
return 0;
}
int main(){
int a[]; // compilation error, array_size missing
return 0;
}
int main(){
int a[2]; // declaration, but can't work without array_size,
// so at compile time it is checked!
return 0;
}
我的问题是,这仅仅是在C语言的声明中赋予array_size的规则,还是在编译时为数组分配内存(仍然是局部变量)
My question is whether it's just a rule to give array_size in declaration in C, or memory is allocated at compile time for array (still local variable)
它如何工作?
根据K& R的C编程,数组是变量. pg 161.
An array is a variable as per C programming by K&R. pg no 161.
推荐答案
声明局部变量时,它的大小在编译时是已知的,但是内存分配是在执行时发生的.
When you declare local variable, the size of it is known at a compile time, but memory allocation occurs during execution time.
因此,在您的示例中,没有大小的数组显然是编译器遇到的问题,因为它不知道要包含在汇编代码中的大小是什么.
So in your examples, array without a size is clearly a problem to compiler, as it doesn't know what is the size to include into assembler code.
如果您不知道数组的大小,则可以始终使用指针类型和malloc
/free
甚至alloca
.前两个在堆上操作,alloca
实际上使用堆栈.
If you don't know the size of an array, you can always use pointer types and malloc
/free
or even alloca
. The first two operate on heap, and alloca
actually uses stack.
值得注意的例外是静态变量.它们的存储已在编译/链接时分配,并且无法在运行时更改.
The notable exception is static variables. The storage for them is allocated at a compile/link time already and can't be changed at runtime.
示例:
int main(int argc, const char *argv[])
{
int a; // a is a sizeof(int) allocated on stack
}
int main(int argc, const char *argv[])
{
int a[2]; // a is a sizeof(int)*2 allocated on stack
}
int main(int argc, const char *argv[])
{
int *a; // a is a sizeof(int*) allocated on stack (pointer)
a = alloca(sizeof(int)*4); // a points to an area with size of 4 integers
// data is allocated on stack
}
int main(int argc, const char *argv[])
{
static int a; // a is allocated in data segment, keeps the value
}
这篇关于什么时候将内存分配给C中的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!