作者LoganChien (简子翔)
看板b97902HW
标题[计程] 变数的储存周期
时间Sat Nov 15 03:57:17 2008
有一天在上刘邦锋老师的计算机程式的时候,老师好像忽然转向助教,
问到:「你们在助教课有讲过 static 吗?」当然,接下来的对话不
是本文的重点,我今天的重点摆在 static。或更进一步来说是
Storage Duration (储存周期)。
其实在 C/C++ 语言中的变数有三种不同的 Storage Duration
(储存周期):
1. Static Storage Duration (静态储存周期)
2. Automatic Storage Duration (自动储存周期)
3. Heap Storage Duration (堆积储存周期)
我将分述如下。
1.
Static Storage Duration
在函式外的全域变数或在函式内但是刻意以
static 关键字修饰的变
数会是属於 Static Storage Duration。他的
生命周期(Lifetime)是
从
程式开始执行的时候开始,程式结束之後才会被释放。整个程式运
行时会占用固定的记忆体空间。以下是若干 Static 变数的范例:
#include <stdlib.h>
int g_variable1; /* Static Storage Duration */
int g_variable2 = 5; /* Static Storage Duration */
int g_array[10]; /* Static Storage Duration */
int main()
{
static int local_static_variable; /* Static Storage Duration */
return EXIT_SUCCESS;
}
Static Storage Duration 的变数会有以下特性:
1.
如果宣告时有被初始化,其值会等於初始值。
2. 如果宣告时没有被初始化,且其型别为
算术型别(Arithmetic
Type),其
值会被初始化为零。
3. 如果宣告时没有被初始化,且其型别为
指标型别,其值会被
初始
化为 NULL。
所以上面的 g_variable1 == 0, local_static_variable == 0,
g_variable2 == 5 。当然,即便是阵列也不例外 a[0] == 0,
a[1] == 0 ... a[9] == 0 。
2.
Automatic Storage Duration
在函式内部的变数、函式的引数如果没有特别声明,就是 Automatic
Storage Duration。
变数的生命周期始於存放变数的视野(Scope)开
始处,止於视野的结束处。例如:
#include <stdlib.h>
int
main()
{
int variable1; /* Automatic Storage Duration */
int variable2 = 0; /* Automatic Storage Duration */
int array1[4]; /* Automatic Storage Duration */
int array2[4] = {1, 2, 3, 4}; /* Automatic Storage Duration */
int array3[4] = {1, 2}; /* Automatic Storage Duration */
{
int i; /* Automatic Storage Duration */
}
/* Now, "i" is dead */
return EXIT_SUCCESS;
}
/* Now, "variable1", "variable2", "array1", "array2" is dead. */
这一个程式之中,variable1, variable2, array1, array2, array3
都是 Automatic Storage Duration,这一类变数有以下特性:
1.
生命周期开始於宣告处,终止於所在的视野结束时。
2. 每一次函式呼叫都会配置独立的记忆体区块。
3. 原则上,
除非有指明,不然所有的
变数不会被初始化。
4. 阵列可能是第三点的例外,
阵列的元素如果有一个有初始值,则
所有的元素都会有初始值。此时没有指定初指值的变数会以 Static
Storage Duration 的方法初使化。
备注:根据第 4 点,array3[2] == 0, array3[3] == 0,有时候我
们会在宣告的後面加上 = {0} 来将整个阵列初始化为 0。不过要注
意的是 = {10} 并非把所有的元素初始化为 10,只有第一个会是
10,其他的都会是 0。
3.
Heap Storage Duration
Heap Storage Duration 是用於动态配置记忆体。
其生命周期是在被
malloc 时开始,结束於 free 的时候。Heap Storage Duration 不
会被初始化。如下面的程式︰
#include <stdlib.h>
int
main()
{
int *my_array = (int *)malloc(sizeof(int) * 10);
free(my_array);
return EXIT_SUCCESS;
}
不过要稍微解说一下,my_array 这一个指标本身是属於 Automatic
Storage Duration,是 may_array 所指向的变数才是 Heap Storage
Duration。
文未附上可以看生命周期的 C++ 程式码。
http://www.csie.ntu.edu.tw/~b97073/bbs/src/lifetime.cpp
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.112.241.166
※ 编辑: LoganChien 来自: 140.112.241.166 (11/15 03:59)