问题描述
大家好,
我发现可以在编译时分配静态内存,因为对象/变量要使用的大小是预定义的.
我的问题是"[在启动应用程序时,[编译器]如何知道操作系统将为该应用程序分配哪个内存位置.],以便所有静态[int x]变量都可以分配内存"?
例如
可执行文件名称:run.exe
========================
代码
========
Hi All,
I found that static memory can be allocated at compile time, as the size the object/variable going to take is predefined.
My question is "how it[compiler] knows which memory location will be assign to the application by OS,[while launching the apps.] so that all the static [int x] variable could allocate memory"?
e.g.
executable name: run.exe
==========================
code
========
void main()
{
int x;//Say ''x'' assigned to->0xFFAB12 memory location while compiling
}
现在重启机器
然后运行run.exe,而无需再次编译
如何知道 0xFFAB12 地址将再次落入OS分配给run.exe的内存区域内?
如果我有一些概念上的问题,请告诉我.
在此先感谢
now restart the machine
and run run.exe without compiling again
how it knows 0xFFAB12 address again will fall under the memory area alloted by OS to run.exe?
if I have some conceptual problem, please let me know.
thanks in advance
推荐答案
void main()
{
int x;\\on the stack, destroyed when main() returns
static int i; \\stored in BSS
}
更一般的示例(请参见堆上存储了什么,存储了什么 [ ^ ])-
More general sample (see What is stored on heap and what is stored on stack?[^]) -
char * str = "Text line 1"; /* 1 */
char * buf0 ; /* 2 */
int main(){
char * str2 = "Text line 2" ; /* 3 */
static char * str3 = str; /* 4 */
char * buf1 ; /* 5 */
buf0 = malloc(BUFSIZ); /* 6 */
buf1 = malloc(BUFSIZ);
return 0;
}
1,这都不分配在堆的堆栈NOR上.而是将其分配为静态数据,并在大多数现代计算机上放入其自己的内存段中.实际的字符串也被分配为静态数据,并放在有思想的机器中的只读段中.
2.只是一个静态分配的指针;静态数据中一个地址的空间.
3.在堆栈上分配了指针,当main返回时将有效释放该指针.由于字符串是常量,因此它与其他字符串一起分配在静态数据空间中.
4.实际上实际上是像2一样分配的.static关键字告诉您不要在堆栈上分配它.
5.但是buf1在堆栈中,并且
6.分配的缓冲区空间在堆上.
1.This is neither allocated on the stack NOR on the heap. Instead it''s allocated as static data, and put into it''s own memory segment on most modern machines. The actual string is also being allocated as static data, and put into a read-only segment in right-thinking machines.
2. Is simply a static allocated pointer; room for one address, in static data.
3. Has the pointer allocated on the stack, and will be effectively deallocated when main returns. The string, since it''s a constant, is allocated in static data space along with the other strings.
4. Is actually allocated exactly like at 2. The static keyword tells you that it''s not to be allocated on the stack.
5. But buf1 is on the stack, and
6. The malloc''ed buffer space is on the heap.
这篇关于静态内存在编译时分配如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!