[計程] 變數的儲存週期

看板b97902HW作者 (簡子翔)時間17年前 (2008/11/15 03:57), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/1
有一天在上劉邦鋒老師的計算機程式的時候,老師好像忽然轉向助教, 問到:「你們在助教課有講過 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)
文章代碼(AID): #197TWUyh (b97902HW)