Global variables are allocated on
the application data segment and persist for the duration of the program. Local
variables (declared within procedures and functions) reside in an application’s
stack. Each time a procedure or function is called, it allocates a set of local
variables; on exit, the local variables are disposed of. Compiler optimization
may eliminate variables earlier.
Note: On Linux, stack size
is set by the environment only.
On Windows, an application’s stack
is defined by two values: the minimum stack size and the maximum
stack size. The values are controlled through the $MINSTACKSIZE
and $MAXSTACKSIZE compiler directives, and default to 16,384 (16K) and
1,048,576 (1M) respectively. An application is guaranteed to have the minimum
stack size available, and an application’s stack is never allowed to grow
larger than the maximum stack size. If there is not enough memory available to
satisfy an application’s minimum stack requirement, Windows will report an
error upon attempting to start the application.
If a Windows application requires
more stack space than specified by the minimum stack size, additional memory is
automatically allocated in 4K increments. If allocation of additional stack
space fails, either because more memory is not available or because the total
size of the stack would exceed the maximum stack size, an EStackOverflow
exception is raised. (Stack overflow checking is completely automatic. The $S
compiler directive, which originally controlled overflow checking, is
maintained for backward compatibility.)
On Windows or Linux, dynamic
variables created with the GetMem or New procedure are
heap-allocated and persist until they are deallocated with FreeMem or Dispose.
Long strings, wide strings, dynamic arrays, variants, and interfaces are heap-allocated, but their memory is managed automatically.
全局变量在应用程序的数据段(data
segment)中分配并且在程序执行的全过程中一直存在。局部变量(声明在过程和函数中的变量)驻留在应用程序的栈(stack)中。每次过程或函数被调用时,将分配一套局部变量;过程或函数退出时,局部殡殓被释放。编译器优化可能除去早先的变量。
注意: 在Linux中,栈的尺寸仅由环境设置。
在Windows中,应用程序的栈通过两个值被定义:最小栈尺寸(minimum stack size)和最大栈尺寸(maximum stack size)。这两个值通过编译指示$MINSTACKSIZE和$MAXSTACKSIZE被控制,缺省值分别是16,384字节(16KB)和1,048,576字节(1MB)。应确保应用程序的最小栈尺寸是可用的,并且应用程序栈的增长不允许超过最大栈尺寸。如果没有足够的可以内存来满足应用程序的最小栈请求,Windows将在试图启动应用程序时报告一个错误。
如果一个Windows应用程序请求的栈空间多于最小栈空间指定的值,那么额外的内存会以4K为增量自动被分配。如果分配额外栈空间失败,那么不是因为多于的内存不可用,就是因为栈的总尺寸超出了既定的最大栈尺寸,这时将引发EStackOverflow异常。(栈溢出检查是自动完成的。$S编译指示最初用来控制栈溢出检查,现在仅维持向后兼容。)
在Windows或Linux中,用过程GetMem或New创建的动态变量是在堆(heap)中分配的,并且一直存在直到被FreeMem或Dispose释放。
长串(long strings)、宽串(wide strings)、动态数组(dynamic arrays)、变体(variants)以及接口(interfaces)等都是堆分配的(heap-allocated),但它们的内存都是被自动管理的。