Ada 的記憶體管理 ── 存取型別、Controlled 型別與儲存池的使用時機

· · Ada, GNAT, 記憶體管理, 存取型別, RAII, 儲存池

分享到 X 分享到 LINE 分享到 Facebook
更新紀錄(僅初版,2026年11月01日 發布)
初次發布

Ada 的規格並不以記憶體回收(GC)為前提。GNAT 的預設配置來源使用 malloc 與 free,不會自動回收不再使用的區域1。相對地,Ada 提供了不使用堆積就能完成的寫法,以及在使用堆積時把規則寫進型別的機制。

本文依下列順序說明 Ada 的記憶體管理。

  1. 把值放在堆疊上。長度在執行時才決定的值,也能不寫 new 就從函式回傳。
  2. 需要堆積時使用存取型別,用型別決定能指向什麼、生命週期到哪裡。
  3. 用 Unchecked_Deallocation 釋放。如名稱所示它沒有檢查,因此要減少直接呼叫的位置。
  4. 把釋放交給 Controlled 型別的 Finalize。這與 C++ 的 RAII 是同樣的思維。
  5. 用儲存池決定配置來源。可以設定上限,或計算配置的次數。

所有範例都以 Ubuntu 24.04 的 GNAT 13.3.0 編譯並執行,輸出原樣刊載。記憶體誤用的確認使用 valgrind 3.22.0。語言規則則以 Ada 2022 的參考手冊(RM)確認。Ada 本身的特色在〈Ada 語言的魅力〉中介紹。

Ada 中值放在哪裡

在 Ada 中,宣告的變數通常放在堆疊上。長度在執行時才決定的陣列,也能不寫 new 就宣告為變數。只有寫了 new 時才會使用堆積(Ada 的術語稱為儲存池)2。

Ada 中值放在哪裡表示宣告的變數放在堆疊上,長度未定的回傳值在 GNAT 中放在次要堆疊上,用 new 建立的值放在存取型別的儲存池中。宣告的變數堆疊長度未定的回傳值次要堆疊(GNAT)用 new 建立的值儲存池預設的池是 malloc 與 free

圖 1: 宣告的變數放在堆疊上,用 new 建立的值放在儲存池中。

將本文處理的機制依放置位置整理如下。

放置位置 配置 釋放 本文章節
堆疊 變數宣告 離開作用範圍時 不用 new 回傳長度未定的值
次要堆疊(GNAT) 回傳長度未定之值的函式 離開呼叫端的作用範圍時 同上
儲存池 new Unchecked_Deallocation,或 Controlled 型別、容器 存取型別之後

圖中實線表示始終成立的關係,虛線表示附帶條件的關係(成立條件寫在詳細頁面中各關係的說明中)。關係的完整清單(共 15 條,附依據與可信度)以及主要概念的定義,彙整在知識地圖詳細頁面(日文)。資料:JSON-LD / Turtle

不用 new 回傳長度未定的值

在 C 中要回傳長度在執行時才決定的字串,一般會讓呼叫端準備緩衝區,或在函式內 malloc 後由呼叫端 free。在 Ada 中,可以直接把長度未定的 String 當作回傳值。

with Ada.Text_IO; use Ada.Text_IO;

procedure Repeat_Demo is
   --  回傳值的長度要到呼叫時才決定
   function Repeat (C : Character; N : Natural) return String is
      Result : constant String (1 .. N) := (others => C);
   begin
      return Result;
   end Repeat;

   N : Natural := 3;
begin
   for I in 1 .. 3 loop
      declare
         Line : constant String := Repeat ('*', N);
      begin
         Put_Line (Line & " length =" & Natural'Image (Line'Length));
      end;
      N := N * 2;
   end loop;
end Repeat_Demo;
*** length = 3
****** length = 6
************ length = 12

這裡既沒有寫 new,也沒有寫釋放。Line 的長度由 Repeat 回傳的值決定。用 valgrind 執行這個程式,堆積的配置是 0 次。

本文環境中的 GNAT 會把這類回傳值放在次要堆疊上。GNAT 繫結器的文件把次要堆疊說明為「放置函式回傳的、長度未定之型別(例如長度未定的 String)的物件之處」3。在許多環境中,次要堆疊會視需要成長,並實作為堆積上相連的區塊3。GNAT 的文件也寫到,只有部分目標平台會對函式回傳值使用次要堆疊4。

我用一個回傳 1 MB 字串 10,000 次的迴圈,確認離開區塊後區域是否會被重複使用。

with Ada.Text_IO; use Ada.Text_IO;

procedure SS_Loop is
   function Repeat (C : Character; N : Natural) return String is
      Result : constant String (1 .. N) := (others => C);
   begin
      return Result;
   end Repeat;

   Total : Long_Long_Integer := 0;
begin
   --  回傳 1 MB 的字串 10,000 次。合計約 10 GB
   for I in 1 .. 10_000 loop
      declare
         Line : constant String := Repeat ('*', 1_000_000);
      begin
         Total := Total + Long_Long_Integer (Line'Length);
      end;
   end loop;
   Put_Line ("total =" & Long_Long_Integer'Image (Total));
end SS_Loop;
total = 10000000000
==32596==     in use at exit: 1,000,048 bytes in 1 blocks
==32596==   total heap usage: 1 allocs, 0 frees, 1,000,048 bytes allocated

即使回傳合計 10 GB 的字串,堆積的配置也只有 1,000,048 位元組的 1 次。這 1 次應該是為了讓次要堆疊成長的區塊,之後的反覆中沒有新的配置。與用 new 建立的值不同,程式這邊不需要撰寫釋放。

次要堆疊的使用方式表示函式回傳長度未定的值時會堆到次要堆疊上,在呼叫端的區塊中使用,離開區塊後就會被歸還。呼叫 Repeat把結果堆到次要堆疊上在 declare 區塊中當作 Line 使用離開區塊歸還堆上的區域

圖 2: 長度未定的回傳值在離開呼叫端的區塊時會被歸還。

GNAT 的這種用法,加上 pragma Restrictions (No_Secondary_Stack) 就能確認。這個限制會在編譯時保證產生的程式碼不參考次要堆疊4。把與上面 Repeat 相同的函式在此限制下編譯,得到以下錯誤。

pragma Restrictions (No_Secondary_Stack);

procedure Nosec is
   function Repeat (C : Character; N : Natural) return String is
      Result : constant String (1 .. N) := (others => C);
   begin
      return Result;
   end Repeat;

   Line : constant String := Repeat ('*', 3);
begin
   null;
end Nosec;
nosec.adb:7:07: error: violation of restriction "No_Secondary_Stack" at line 1
nosec.adb:10:04: error: violation of restriction "No_Secondary_Stack" at line 1
nosec.adb:10:30: error: violation of restriction "No_Secondary_Stack" at line 1

在加上這個限制的程式碼中,要改成由呼叫端準備長度已定的陣列,函式再寫入其中的形式。

用存取型別決定「能指向什麼」

需要放在堆積上的情況,是希望建立的值在作用範圍外也能使用,或像串列和樹那樣讓元素彼此連結。在 Ada 中,這時使用存取型別。存取型別近似 C 的指標,但能指向什麼要由型別宣告決定2。

池專屬存取型別與一般存取型別

只用 access 宣告的型別是池專屬存取型別,只能指向用該型別的 new 建立的值(該儲存池的元素)。用 access all 宣告的型別是一般存取型別,也能指向加上 aliased 宣告的變數2。

with Ada.Text_IO; use Ada.Text_IO;

procedure Access_Kinds is
   --  池專屬存取型別:只能指向以 new 配置的東西
   type Int_Ptr is access Integer;

   --  一般存取型別:也能指向 aliased 的變數
   type Int_Ref is access all Integer;

   P : constant Int_Ptr := new Integer'(10);

   Counter : aliased Integer := 20;
   R       : constant Int_Ref := Counter'Access;
begin
   R.all := R.all + 1;
   Put_Line ("P.all   =" & Integer'Image (P.all));
   Put_Line ("Counter =" & Integer'Image (Counter));
end Access_Kinds;
P.all   = 10
Counter = 21

反過來的組合會成為編譯錯誤:想用池專屬型別指向變數的情況,以及想指向沒有加 aliased 的變數的情況。

procedure Access_Errors is
   type Int_Ptr is access Integer;
   type Int_Ref is access all Integer;

   Plain   : Integer := 1;
   Counter : aliased Integer := 2;

   P1 : Int_Ptr := Counter'Access;  --  池專屬型別不能指向變數
   R1 : Int_Ref := Plain'Access;    --  不能指向非 aliased 的變數
begin
   null;
end Access_Errors;
access_errors.adb:8:27: error: result must be general access type
access_errors.adb:8:27: error: add "all" to type "Int_Ptr" defined at line 2
access_errors.adb:9:20: error: prefix of "Access" attribute must be aliased

多虧這條規則,可以從宣告讀出哪些變數可能被指標指向。

存取型別的種類與能指向的對象表示池專屬存取型別只能指向用 new 建立的值,一般存取型別除了用 new 建立的值之外,也能指向加上 aliased 的變數。池專屬存取型別(access)用 new 建立的值一般存取型別(access all)加上 aliased 的變數沒有 aliased 的變數任何存取型別都不能指向

圖 3: 只有一般存取型別能指向加上 aliased 的變數。

生命週期檢查(可存取性檢查)

C 常見的錯誤之一,是把函式區域變數的位址存到離開函式後仍會留下的地方。Ada 以可存取性檢查防止這種錯誤。若變數的生命週期(可存取性層級)比存取型別的生命週期短,就不能把指向該變數的值放進該型別5。

在編譯時就能得知的情況下,會成為編譯錯誤。下面的套件想把指向引數變數的值,存到程式庫層級(保留到程式結束)的變數 Saved 中。

package Registry is
   type Int_Ref is access all Integer;

   Saved : Int_Ref;  --  程式庫層級的變數。保留到程式結束

   procedure Remember_Static (X : aliased in out Integer);
end Registry;

package body Registry is
   procedure Remember_Static (X : aliased in out Integer) is
   begin
      Saved := X'Access;
   end Remember_Static;
end Registry;
registry.adb:4:16: error: non-local pointer cannot point to local object

把引數改為匿名存取型別(access Integer)後,呼叫端會傳入什麼,在編譯時無從得知。這種情況下檢查會在執行時進行,失敗時會引發 Program_Error5。

package Registry is
   type Int_Ref is access all Integer;

   Saved : Int_Ref;  --  程式庫層級的變數。保留到程式結束

   Global_Value : aliased Integer := 100;

   procedure Remember (X : access Integer);
end Registry;

package body Registry is
   procedure Remember (X : access Integer) is
   begin
      Saved := Int_Ref (X);  --  在執行時確認實際引數的生命週期
   end Remember;
end Registry;
with Ada.Text_IO; use Ada.Text_IO;
with Registry;    use Registry;

procedure Remember_Demo is
   procedure Try_Local is
      Local : aliased Integer := 1;
   begin
      Remember (Local'Access);
      Put_Line ("saved a local object");
   end Try_Local;
begin
   Remember (Global_Value'Access);
   Put_Line ("saved:" & Integer'Image (Saved.all));

   Try_Local;
end Remember_Demo;
saved: 100

raised PROGRAM_ERROR : registry.adb:4 accessibility check failed

傳入程式庫層級的 Global_Value 時可以保存,傳入 Try_Local 的區域變數時,在保存的時間點就停止了。在 C 中做同樣的事,保存是可以的,離開函式後再使用那個值就會成為未定義行為。在 Ada 中,會在試圖保存的那一行停止。

可存取性檢查進行的時間點表示想把指向生命週期較短之變數的值放進生命週期較長的存取型別時,若編譯時能得知就成為編譯錯誤,若像匿名存取型別的引數那樣要到執行時才知道,就會成為 Program_Error。能得知無法得知(匿名存取型別的引數)保存指向生命週期較短之變數的值編譯時能否得知生命週期編譯錯誤在執行時檢查Program_Error

圖 4: 生命週期檢查在能得知時於編譯時進行,無法得知時於執行時進行。

不允許 null 的存取型別

存取型別的變數若沒有寫初始值,就會是 null。在引數或變數的型別加上 not null,該型別就不再包含 null2。傳入 null 時,會在呼叫的時間點成為 Constraint_Error。

with Ada.Text_IO; use Ada.Text_IO;

procedure Not_Null_Demo is
   type Int_Ptr is access Integer;

   --  由型別這邊保證引數不會是 null
   procedure Show (P : not null Int_Ptr) is
   begin
      Put_Line ("value =" & Integer'Image (P.all));
   end Show;

   A : constant Int_Ptr := new Integer'(5);
   B : Int_Ptr;  --  沒寫初始值的存取型別變數會是 null
begin
   Show (A);
   Show (B);
end Not_Null_Demo;
not_null_demo.adb:13:04: warning: variable "B" is read but never assigned [-gnatwv]
value = 5

raised CONSTRAINT_ERROR : not_null_demo.adb:16 access check failed

第 1 個是編譯時的警告,第 2 個是執行時的輸出。在 Show 中不再需要確認 null,而傳入 null 時,回報的不是 Show 內部,而是呼叫的那一行(第 16 行)。

用 Unchecked_Deallocation 釋放

用 new 配置的值,要用實例化 Ada.Unchecked_Deallocation 而得的程序釋放。依慣例這個程序命名為 Free。依 RM 的規則,Free (X) 之後 X 會成為 null,若 X 已經是 null 則什麼都不做6。

如名稱中的 Unchecked 所示,這個程序不會檢查指向同一區域的其他指標。下面的例子在 A 與 B 指向同一個值的狀態下釋放 A。

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Unchecked_Deallocation;

procedure Dangling_Demo is
   type Int_Ptr is access Integer;
   procedure Free is new Ada.Unchecked_Deallocation (Integer, Int_Ptr);

   A : Int_Ptr := new Integer'(42);
   B : constant Int_Ptr := A;  --  指向同一個物件的第 2 個指標
begin
   Free (A);
   Put_Line ("A = null : " & Boolean'Image (A = null));
   Put_Line ("B = null : " & Boolean'Image (B = null));
   Put_Line ("B.all    =" & Integer'Image (B.all));  --  讀取已釋放的區域
end Dangling_Demo;
A = null : TRUE
B = null : FALSE
B.all    = 1613378576

A 成為 null,但 B 仍保有原來的位址。RM 把這種指向不存在之物件的值稱為懸置參考,並把參考它時的執行定為 erroneous(結果未由規格定義)6。在 GNAT 13.3 上沒有拋出例外,B.all 回傳了不是 42 的值。用 valgrind 執行同一個程式,會回報讀取了已釋放的區域。

==6788== Invalid read of size 4
==6788==    at 0x10BAD8: _ada_dangling_demo (dangling_demo.adb:14)
==6788==    by 0x10B8DE: main (b~dangling_demo.adb:248)
==6788==  Address 0x5004040 is 0 bytes inside a block of size 4 free'd
==6788==    at 0x484988F: free (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==6788==    by 0x4B08E48: __gnat_free (in /usr/lib/x86_64-linux-gnu/libgnat-13.so)
==6788==    by 0x10B954: _ada_dangling_demo (dangling_demo.adb:11)

從這段追蹤也能看出,GNAT 的預設池是透過 __gnat_free 呼叫 C 的 free。

Unchecked_Deallocation 之後留下的指標表示 Free(A) 讓 A 成為 null,但原本指向同一區域的 B 仍保有原來的位址,參考 B 會成為 erroneous,valgrind 會將其回報為讀取已釋放的區域。A 與 B 指向同一個值Free(A)A 成為 nullB 仍是原來的位址讀取 B.allerroneous(結果未定義)valgrind: Invalid read

圖 5: Free 只會把傳入的變數設為 null,指向同一區域的其他變數會留下來。

反過來說,不釋放的話區域就不會歸還。下面的迴圈把 new 的結果 1,000 次放進同一個變數,遺失了指向先前值的指標。

procedure Leak_Demo is
   type Int_Ptr is access Integer;
   P : Int_Ptr;
begin
   for I in 1 .. 1_000 loop
      P := new Integer'(I);  --  指向先前區域的指標在這裡遺失
   end loop;
end Leak_Demo;
==10504==     in use at exit: 4,000 bytes in 1,000 blocks
==10504== 4,000 bytes in 1,000 blocks are definitely lost in loss record 1 of 1
==10504==    at 0x4846828: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==10504==    by 0x4B08DE1: __gnat_malloc (in /usr/lib/x86_64-linux-gnu/libgnat-13.so)
==10504==    by 0x10A6FF: _ada_leak_demo (leak_demo.adb:6)

在有 GC 的語言中會被回收的區域,在 GNAT 中一直留到程式結束。GNAT 的文件也寫到,預設池(System.Pool_Global)使用 malloc 與 free,不做自動回收1。

規格這邊也不以 GC 為前提。Ada 2012 修訂時,參考手冊刪除了關於記憶體回收的敘述。附註解的參考手冊(AARM)寫到,Ada 2012 改為提供子池,而且子池遠比 GC 容易預測7。

SPARK 的所有權規則

Ada 的子集語言 SPARK 對存取型別施加所有權規則。能讀寫已配置區域的存取值,同時只能有一個8。我把與前面 Dangling_Demo 相同的步驟寫成 SPARK 程式碼,以 GNATprove 15.1 加上 --mode=check_all 進行檢查。

with Ada.Unchecked_Deallocation;

procedure Dangling_Spark with SPARK_Mode is
   type Int_Ptr is access Integer;
   procedure Free is new Ada.Unchecked_Deallocation (Integer, Int_Ptr);

   A : Int_Ptr := new Integer'(42);
   B : Int_Ptr := A;  --  A 的所有權轉移給 B
   V : Integer;
begin
   Free (A);
   V := B.all;
   Free (B);
end Dangling_Spark;
dangling_spark.adb:11:10: error: "A" is not readable
   11 |   Free (A);
      |         ^ here
  object was moved at line 8 [E0010]
    8 |   B : Int_Ptr := A;  --  A 的所有權轉移給 B
      |                  ^ here

在 B := A 的時間點所有權轉移給 B,因此試圖釋放 A 的那一行在檢查中被擋下。以 GNAT 編譯並執行的 Dangling_Demo 中,同樣的錯誤沒有拋出例外,直到用 valgrind 才發現。用 SPARK 進行證明的方式,在〈Proving AI-Written Code with SPARK〉(英文)中說明。

以 Ada 與 SPARK 處理同一個錯誤時的差異表示用兩個指標指向同一區域並釋放其中之一的錯誤,以 Ada 執行時不會被偵測而讀取已釋放的區域,以 SPARK 檢查時 GNATprove 會以所有權轉移為由回報錯誤。用兩個指標指向同一區域並釋放以 Ada 執行以 SPARK 檢查未被偵測而讀取已釋放的區域GNATprove 以所有權轉移回報錯誤

圖 6: 同一個錯誤在 SPARK 中會因所有權規則在檢查階段被發現。

若維持以 Ada 撰寫,就把呼叫 Free 的地方限制在值的擁有者明確的少數位置。其代表就是接下來的 Controlled 型別。

用 Controlled 型別在離開作用範圍時收尾

繼承 Ada.Finalization 的 Controlled 型別後,可以覆寫 3 個程序9。

程序 呼叫時機
Initialize 沒有寫初始值就宣告時
Adjust 因指派而複製之後,對複製目的地呼叫
Finalize 離開作用範圍時、因指派而被覆寫之前、以 Free 釋放時

為了確認呼叫的順序,我做了一個每次被呼叫都顯示名稱的型別。在 Adjust 中把名稱改為小寫,以便看出是被複製的一方。

with Ada.Finalization;

package Tracked is
   type Resource is new Ada.Finalization.Controlled with record
      Name : Character := '?';
   end record;

   overriding procedure Initialize (R : in out Resource);
   overriding procedure Adjust     (R : in out Resource);
   overriding procedure Finalize   (R : in out Resource);
end Tracked;
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Text_IO;             use Ada.Text_IO;

package body Tracked is
   overriding procedure Initialize (R : in out Resource) is
   begin
      Put_Line ("  Initialize " & R.Name);
   end Initialize;

   --  為了看出是被複製的一方,把名稱改為小寫
   overriding procedure Adjust (R : in out Resource) is
   begin
      Put_Line ("  Adjust     " & R.Name & " -> " & To_Lower (R.Name));
      R.Name := To_Lower (R.Name);
   end Adjust;

   overriding procedure Finalize (R : in out Resource) is
   begin
      Put_Line ("  Finalize   " & R.Name);
   end Finalize;
end Tracked;
with Ada.Finalization;
with Ada.Text_IO; use Ada.Text_IO;
with Tracked;     use Tracked;

procedure Raii_Demo is
begin
   Put_Line ("enter block");
   declare
      --  沒有寫初始值,因此會呼叫 Initialize
      A : Resource;
      --  以彙總(aggregate)初始化,因此不會呼叫 Initialize
      B : Resource := (Ada.Finalization.Controlled with Name => 'B');
   begin
      A.Name := 'A';
      Put_Line ("assign B := A");
      B := A;
      Put_Line ("leave block");
   end;
   Put_Line ("after block");

   Put_Line ("enter block with exception");
   begin
      declare
         C : Resource;
      begin
         C.Name := 'C';
         raise Constraint_Error;
      end;
   exception
      when Constraint_Error =>
         Put_Line ("handled Constraint_Error");
   end;
end Raii_Demo;
enter block
  Initialize ?
assign B := A
  Finalize   B
  Adjust     A -> a
leave block
  Finalize   a
  Finalize   A
after block
enter block with exception
  Initialize ?
  Finalize   C
handled Constraint_Error

從輸出可以讀出以下幾點。

  • Initialize 只對沒有初始值的 A 呼叫,以彙總初始化的 B 沒有呼叫。RM 也規定在預設初始化時呼叫 Initialize9。
  • 在 B := A 中,先呼叫被覆寫之 B 的 Finalize,接著呼叫複製後之值的 Adjust。
  • 離開區塊時,依與宣告相反的順序(B 的複本、A 的順序)呼叫 Finalize。
  • 因例外跳出區塊的 C 也呼叫了 Finalize。
Controlled 型別之程序的呼叫順序表示沒有初始值的宣告會呼叫 Initialize,指派時會呼叫被覆寫一方的 Finalize 與複製目的地的 Adjust,離開作用範圍與因例外跳出時,會依與宣告相反的順序呼叫 Finalize。不寫初始值就宣告Initialize執行 B := A對 B 的舊值 Finalize對複製的值 Adjust離開作用範圍、因例外跳出依與宣告相反的順序 Finalize

圖 7: 指派時會呼叫舊值的 Finalize 與複本的 Adjust,離開作用範圍時則依相反順序呼叫 Finalize。

因例外跳出時也會呼叫 Finalize,因此把堆積的釋放寫在這裡,呼叫端就不會忘記寫 Free。這與 C++ 在解構子中撰寫釋放的 RAII 是同樣的思維。C++ 這邊的 RAII 在〈多執行緒實務最佳實踐 C++ 篇〉中說明。

不希望被複製的資源要使用 Limited_Controlled。它會成為不能指派的型別,因此沒有 Adjust。下一節的例子使用的就是這個。

用儲存池決定配置來源

new 從哪裡取得區域,由每個存取型別的儲存池決定。不指定任何東西時會使用實作的預設池,在 GNAT 中就是使用 malloc 與 free 的 System.Pool_Global1。在 Ada 中,可以依型別替換這個池,或為它設定上限10。

用 Storage_Size 設定上限

為存取型別指定 Storage_Size 後,該型別的 new 會從擁有至少指定大小區域的、由實作定義的池中配置。區域用完時,不再配置而是引發 Storage_Error10。

with Ada.Text_IO; use Ada.Text_IO;

procedure Bounded_Demo is
   --  把這個型別的 new 可用的區域限制為 64 位元組
   type Int_Ptr is access Integer
     with Storage_Size => 64;

   P     : Int_Ptr;
   Count : Natural := 0;
begin
   loop
      P := new Integer'(Count);
      Count := Count + 1;
   end loop;
exception
   when Storage_Error =>
      Put_Line ("Storage_Error after" & Natural'Image (Count) & " allocations");
end Bounded_Demo;
Storage_Error after 8 allocations

配置 8 次之後,第 9 次的 new 成為 Storage_Error。每次配置使用的量由實作決定,因此次數無法單純從 Integer 的大小求出。這個池的區域在離開宣告存取型別的作用範圍時會被回收10。在想事先決定記憶體上限的嵌入式裝置,或長時間執行的處理中,想為每個型別的使用量設定額度時可以使用。

指定了 Storage_Size 的存取型別的配置表示以指定了 Storage_Size 的存取型別執行 new 時,池中有空間就配置,用完則成為 Storage_Error,離開宣告存取型別的作用範圍時,池的區域會被回收。有沒有以 Int_Ptr 執行 new池中是否有空間配置Storage_Error離開宣告存取型別的作用範圍回收池的區域

圖 8: 指定了 Storage_Size 的型別,額度用完會成為 Storage_Error,離開作用範圍時連同額度一起回收。

自己撰寫池

繼承 System.Storage_Pools 的 Root_Storage_Pool,並覆寫 Allocate、Deallocate、Storage_Size,就能做出自己的池10。下面的池會計算配置與釋放的次數以及使用中的位元組數,實際的配置則交給 GNAT 的預設池。System.Pool_Global 是 GNAT 專有的單元,在其他實作中需要別的配置來源。

with System;
with System.Storage_Elements; use System.Storage_Elements;
with System.Storage_Pools;    use System.Storage_Pools;

package Counting_Pools is
   --  計算配置與釋放次數、使用中位元組數的池
   type Counting_Pool is new Root_Storage_Pool with record
      Allocations   : Natural       := 0;
      Deallocations : Natural       := 0;
      In_Use        : Storage_Count := 0;
   end record;

   overriding procedure Allocate
     (Pool                     : in out Counting_Pool;
      Storage_Address          : out System.Address;
      Size_In_Storage_Elements : Storage_Count;
      Alignment                : Storage_Count);

   overriding procedure Deallocate
     (Pool                     : in out Counting_Pool;
      Storage_Address          : System.Address;
      Size_In_Storage_Elements : Storage_Count;
      Alignment                : Storage_Count);

   overriding function Storage_Size
     (Pool : Counting_Pool) return Storage_Count;

   procedure Report (Pool : Counting_Pool; Label : String);
end Counting_Pools;
with Ada.Text_IO;      use Ada.Text_IO;
with System.Pool_Global;  --  GNAT 的預設池(GNAT 專有的單元)

package body Counting_Pools is
   Backing : System.Pool_Global.Unbounded_No_Reclaim_Pool
     renames System.Pool_Global.Global_Pool_Object;

   overriding procedure Allocate
     (Pool                     : in out Counting_Pool;
      Storage_Address          : out System.Address;
      Size_In_Storage_Elements : Storage_Count;
      Alignment                : Storage_Count) is
   begin
      Backing.Allocate (Storage_Address, Size_In_Storage_Elements, Alignment);
      Pool.Allocations := Pool.Allocations + 1;
      Pool.In_Use      := Pool.In_Use + Size_In_Storage_Elements;
   end Allocate;

   overriding procedure Deallocate
     (Pool                     : in out Counting_Pool;
      Storage_Address          : System.Address;
      Size_In_Storage_Elements : Storage_Count;
      Alignment                : Storage_Count) is
   begin
      Backing.Deallocate (Storage_Address, Size_In_Storage_Elements, Alignment);
      Pool.Deallocations := Pool.Deallocations + 1;
      Pool.In_Use        := Pool.In_Use - Size_In_Storage_Elements;
   end Deallocate;

   overriding function Storage_Size
     (Pool : Counting_Pool) return Storage_Count is
   begin
      return Storage_Count'Last;  --  不設上限
   end Storage_Size;

   procedure Report (Pool : Counting_Pool; Label : String) is
   begin
      Put_Line (Label & ": allocations =" & Natural'Image (Pool.Allocations)
                & ", deallocations =" & Natural'Image (Pool.Deallocations)
                & ", in use =" & Storage_Count'Image (Pool.In_Use) & " bytes");
   end Report;
end Counting_Pools;

把這個池與上一節的 Limited_Controlled 組合起來。Buffer 是只持有一個堆積上的陣列,並在 Finalize 中釋放它的型別。存取型別 Byte_Array_Ptr 指定了 Storage_Pool => Pool,讓這個型別的 new 經過 Counting_Pool。

with Ada.Finalization;
with Counting_Pools;

package Buffers is
   Pool : Counting_Pools.Counting_Pool;

   type Byte_Array is array (Positive range <>) of Character;
   type Byte_Array_Ptr is access Byte_Array
     with Storage_Pool => Pool;

   --  只持有一個堆積上的陣列,離開作用範圍時釋放它的型別
   type Buffer is new Ada.Finalization.Limited_Controlled with record
      Data : Byte_Array_Ptr;
   end record;

   procedure Allocate (B : in out Buffer; Length : Positive);
   overriding procedure Finalize (B : in out Buffer);
end Buffers;
with Ada.Unchecked_Deallocation;

package body Buffers is
   procedure Free is new Ada.Unchecked_Deallocation (Byte_Array, Byte_Array_Ptr);

   procedure Allocate (B : in out Buffer; Length : Positive) is
   begin
      Free (B.Data);  --  已經持有就先歸還(null 則什麼都不做)
      B.Data := new Byte_Array (1 .. Length);
   end Allocate;

   overriding procedure Finalize (B : in out Buffer) is
   begin
      Free (B.Data);
   end Finalize;
end Buffers;
with Counting_Pools; use Counting_Pools;
with Buffers;        use Buffers;

procedure Pool_Demo is
begin
   Report (Pool, "start      ");

   declare
      X, Y : Buffer;
   begin
      Allocate (X, 100);
      Allocate (Y, 200);
      Allocate (X, 50);  --  先歸還 X 的 100 位元組,再重新取得 50 位元組
      Report (Pool, "in block   ");
   end;  --  X 與 Y 的 Finalize 會釋放剩下的部分

   Report (Pool, "after block");
end Pool_Demo;
start      : allocations = 0, deallocations = 0, in use = 0 bytes
in block   : allocations = 3, deallocations = 1, in use = 268 bytes
after block: allocations = 3, deallocations = 3, in use = 0 bytes

區塊內配置 3 次、釋放 1 次,離開區塊後配置與釋放的次數一致,使用量回到 0。Pool_Demo 一次也沒有呼叫 Free。釋放只在 Allocate 中的重新取得,以及 Buffer 的 Finalize 中進行。用 valgrind 的 --leak-check=full 執行,這個程式也沒有任何回報。

使用中的 268 位元組,比元素數的合計(250)更多。把傳給 Allocate 的大小逐次顯示,結果是 108、208、60 位元組。比元素數多出的部分,應該包含了用來保存陣列索引範圍的區域等,但內容由實作決定,本文沒有確認。

經過計數池的配置與釋放表示 Buffer 型別的 new 與 Free 會呼叫存取型別所指定之 Counting_Pool 的 Allocate 與 Deallocate,Counting_Pool 計算次數後,把配置與釋放交給 GNAT 的預設池。Buffer 中的 newCounting_Pool 的 AllocateFinalize 中的 FreeCounting_Pool 的 Deallocate計算次數與使用量GNAT 的預設池malloc 與 free

圖 9: 為存取型別指定池之後,該型別的 new 與 Free 全都會經過那個池。

像這樣計算配置的池,可以在測試中用來確認「處理之後使用量是否回到 0」。GNAT 也提供了能偵測已釋放區域之參考等問題的 GNAT.Debug_Pools11。本文沒有試用。

子池

Ada 2012 加入了把一個池分成多個子池的 System.Storage_Pools.Subpools12。可以像 new (Subpool) T 這樣指定配置來源的子池,並能以子池為單位一次釋放。適合在每個處理單位配置的值,最後一起丟棄的用法。本文沒有執行子池的例子。

用標準容器減少手寫的指標

組合存取型別與 Controlled 型別就能做出安全的型別,但不必在每次需要可變長度的序列或字典時都自己撰寫。Ada 2005 之後的 Ada.Containers 中有向量、串列、對應、集合等13,元素的配置與釋放由容器負責。

像長度各不相同的 String 這樣、大小隨值而異的元素,要放進名稱帶有 Indefinite_ 的容器。

with Ada.Containers.Indefinite_Vectors;
with Ada.Text_IO; use Ada.Text_IO;

procedure Containers_Demo is
   --  可以把長度不同的 String 直接當作元素
   package String_Vectors is new Ada.Containers.Indefinite_Vectors
     (Index_Type => Positive, Element_Type => String);

   Names : String_Vectors.Vector;
begin
   Names.Append ("Ada");
   Names.Append ("SPARK");
   Names.Append ("GNAT");

   for Name of Names loop
      Put_Line (Name & ":" & Natural'Image (Name'Length));
   end loop;

   Names.Delete (2);
   Put_Line ("length after delete:" & Ada.Containers.Count_Type'Image (Names.Length));
end Containers_Demo;
Ada: 3
SPARK: 5
GNAT: 4
length after delete: 2

這個程式中既沒有 new 也沒有 Free。用 valgrind 執行,結束時的使用量是 0 位元組,配置的區塊全都已釋放。

==10040==     in use at exit: 0 bytes in 0 blocks
==10040== All heap blocks were freed -- no leaks are possible

容器是泛型套件,因此要傳入元素型別來實例化。泛型的機制在〈Ada 的泛型程式設計〉中說明。

選擇使用哪種機制的準則

到目前為止的機制,由上而下依序檢討就容易選擇。

在 Ada 中選擇記憶體處理方式的順序表示先考慮能否以值宣告,要增減元素就用容器,需要獨特的結構就用存取型別與 Controlled 型別,想決定配置來源或上限就用儲存池的檢討順序。能不能足夠不夠想決定能否以值宣告、回傳維持變數、回傳值的形式處理序列或字典是否足夠Ada.Containers存取型別與 Controlled 型別是否想決定配置來源或上限儲存池

圖 10: 無法以值處理時考慮容器,仍不夠時再考慮存取型別與 Controlled 型別。

  • 若只是長度在執行時才決定,就以值的形式宣告,並從函式回傳。不需要 new。
  • 若要增加或刪除元素,就使用 Ada.Containers。
  • 若需要樹或圖這類獨特的結構,就用存取型別建立,並把呼叫 Free 的地方限制在 Controlled 型別的 Finalize 等少數位置。用 aliased 與 not null 把能指向的對象以及 null 的有無寫進型別。
  • 想決定配置的上限或配置來源時,就指定 Storage_Size 或儲存池。

即使用 Ada 的型別表示記憶體的使用方式,編譯器也不會擋下 Unchecked_Deallocation 的誤用。要減少這部分,剩下的地方則用 valgrind 或計算配置的池來確認。想連所有權規則都檢查的部分,也可以用 SPARK 撰寫。

在 .NET 這類有 GC 的環境中,記憶體持續增加時的調查方式,整理在〈在 .NET 中區分 GC 延遲與記憶體洩漏〉中。

相關文章

參考連結

  1. GNAT Reference Manual, System.Pool_Global (s-pooglo.ads). 與預設儲存池相同的池,使用 malloc 與 free,不做自動回收。 ↩ ↩2 ↩3

  2. Ada Reference Manual (Ada 2022), 3.10 Access Types. 池專屬存取型別與一般存取型別、aliased、null 排除(not null)。 ↩ ↩2 ↩3 ↩4

  3. GNAT User’s Guide, Switches for gnatbind. -D 參數說明中提到的次要堆疊的角色與實作。 ↩ ↩2

  4. GNAT Reference Manual, No_Secondary_Stack. 在編譯時保證產生的程式碼不參考次要堆疊的限制。 ↩ ↩2

  5. Ada Reference Manual (Ada 2022), 3.10.2 Operations of Access Types. 可存取性層級,以及檢查失敗時的 Program_Error。 ↩ ↩2

  6. Ada Reference Manual (Ada 2022), 13.11.2 Unchecked Storage Deallocation. Free (X) 之後 X 會成為 null,以及懸置參考與 erroneous 的執行。 ↩ ↩2

  7. Annotated Ada Reference Manual (Ada 2022), 13.11.3 Default Storage Pools. 「Wording Changes from Ada 2005」的 9.d/3。Ada 2012 刪除了記憶體回收的敘述,並提供了子池。 ↩

  8. AdaCore, SPARK User’s Guide, Language Restrictions. 存取型別與配置遵循所有權規則,能讀寫已配置區域的存取值同時只能有一個(Memory Ownership Policy)。 ↩

  9. Ada Reference Manual (Ada 2022), 7.6 Assignment and Finalization. Controlled 與 Limited_Controlled,Initialize、Adjust、Finalize 被呼叫的條件與指派的步驟。 ↩ ↩2

  10. Ada Reference Manual (Ada 2022), 13.11 Storage Management. Root_Storage_Pool 與 Allocate、Deallocate、Storage_Size,指定了 Storage_Size 之型別的池與 Storage_Error。 ↩ ↩2 ↩3 ↩4

  11. GNAT User’s Guide, The GNAT Debug Pool Facility. 每次參考時都確認是否指向正確配置之區域的 GNAT.Debug_Pools。 ↩

  12. Ada Reference Manual (Ada 2022), 13.11.4 Storage Subpools. 以 System.Storage_Pools.Subpools 實現的子池。 ↩

  13. Ada Reference Manual (Ada 2022), A.18 Containers. Ada.Containers 的向量、串列、對應、集合,以及名稱帶有 Indefinite_ 的容器。 ↩

共用相同標籤的最新文章。能以相近的主題延伸理解。

與本文相近的主題頁面。以本文為起點,可進一步連到相關服務與其他文章。

本文連結到以下服務頁面,歡迎從最接近的入口查看。

常見問題

整理諮詢這個主題時常見的問題。

Ada 有記憶體回收嗎?
GNAT 的預設儲存池以 malloc 和 free 進行配置與釋放,不會自動回收不再使用的區域。Ada 2012 修訂時,參考手冊刪除了關於記憶體回收的敘述,改為加入可預測性較高的子池。釋放要用 Unchecked_Deallocation 進行,或交給 Controlled 型別或標準容器。
回傳長度在執行時才決定的字串的函式,會使用堆積嗎?
不寫 new 也能回傳。GNAT 依目標平台不同,會對回傳長度未定之陣列或記錄的函式使用次要堆疊。在 Linux x86_64 的 GNAT 13.3 上,即使回傳 1 MB 的字串 10,000 次,堆積的配置也只有約 1 MB 的 1 次。加上 pragma Restrictions (No_Secondary_Stack) 後,這種使用會成為編譯錯誤。
用 Unchecked_Deallocation 釋放之後,指向同一區域的其他指標會怎樣?
傳給釋放的變數會變成 null,但原本指向同一區域的其他變數仍保有原來的位址。參考它時,執行會成為 erroneous(結果未由規格定義)。在 GNAT 13.3 上試驗時沒有拋出例外,valgrind 將其回報為讀取已釋放的區域。
Ada 中有相當於 C++ RAII 的機制嗎?
有,就是 Ada.Finalization 的 Controlled 型別與 Limited_Controlled 型別。覆寫 Finalize 後,離開作用範圍時以及因例外跳出時都會呼叫它。把堆積的釋放寫在這裡,呼叫端就不必撰寫釋放。

作者檔案

本文作者的個人檔案頁面。

Go Komura

小村軟體有限公司 代表

以 Windows 軟體開發、技術諮詢與故障調查為中心,擅長處理仍留有既有資產的專案,以及原因難以看清的故障調查。

回到部落格一覽