Ada 的内存管理 —— 访问类型、Controlled 类型与存储池的使用时机

· · Ada, GNAT, 内存管理, 访问类型, RAII, 存储池

分享到 X 分享到微博 分享到 QQ
更新记录(仅首版,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 软件开发、技术咨询与故障排查为中心,擅长保留有既有资产的项目,以及原因难以看清的故障调查。

返回博客列表