Ada में memory management ── access types, controlled types और storage pools का सही इस्तेमाल

· · Ada, GNAT, Memory Management, Access Types, RAII, Storage Pools

X पर पोस्ट करें
संशोधन इतिहास (केवल पहला संस्करण, 1 Nov 2026 को प्रकाशित)
पहला प्रकाशन

Ada standard garbage collection (GC) मानकर नहीं चलता। GNAT का default allocator malloc और free इस्तेमाल करता है और जो memory अब काम में नहीं है उसे अपने-आप reclaim नहीं करता1। इसके बजाय Ada में heap से बचने वाले code लिखने के तरीके हैं, और heap इस्तेमाल करते समय लागू होने वाले rules को type में लिखने के mechanisms हैं।

यह article Ada के memory management को इस क्रम में समझाता है:

  1. Values को stack पर रखें। Runtime पर तय होने वाली length वाली values भी new लिखे बिना functions से return की जा सकती हैं।
  2. Heap चाहिए तो access types इस्तेमाल करें, और type से तय करें कि वह क्या point कर सकता है और उसकी lifetime कहाँ तक है।
  3. Deallocation Unchecked_Deallocation से करें। नाम के मुताबिक इसमें कोई check नहीं है, इसलिए इसे सीधे call करने वाली जगहें कम रखें।
  4. Deallocation को controlled type के Finalize पर छोड़ दें। यह C++ के RAII वाला ही idea है।
  5. Memory कहाँ से आए, यह storage pools से तय करें। Limit लगा सकते हैं और allocations गिन सकते हैं।

सभी examples Ubuntu 24.04 पर GNAT 13.3.0 से compile और run किए गए हैं, और output जैसा का तैसा दिखाया गया है। Memory के गलत इस्तेमाल को check करने के लिए valgrind 3.22.0 इस्तेमाल किया। Language rules Ada 2022 Reference Manual (RM) से verify किए हैं। Ada की खुद की खूबियाँ “The Appeal of the Ada Language” (English) में बताई गई हैं।

Ada में values कहाँ रखी जाती हैं

Ada में declare किए गए variables आम तौर पर stack पर रखे जाते हैं। Runtime पर तय होने वाली length वाले arrays को भी new लिखे बिना variable के रूप में declare किया जा सकता है। Heap (Ada की भाषा में storage pool) तब इस्तेमाल होता है जब आप new लिखते हैं2।

Ada में values कहाँ रखी जाती हैंDeclare किए गए variables stack पर, unknown length वाली return values GNAT में secondary stack पर, और new से बनी values access type के storage pool में रखी जाती हैं, यह दिखाता है।Declare किए गए variablesStackUnknown length वाली return valuesSecondary stack (GNAT)new से बनी valuesStorage poolDefault pool malloc और free इस्तेमाल करता है

चित्र 1: Declare किए गए variables stack पर, और new से बनी values storage pool में रखी जाती हैं।

Memory कहाँ रहती है, इसके हिसाब से इस article के mechanisms ऐसे हैं।

जगह Allocation Deallocation इस article का section
Stack Variable declaration Scope से निकलते समय Unknown length की values new के बिना return करना
Secondary stack (GNAT) Unknown length की value return करने वाला function Caller के scope से निकलते समय ऊपर जैसा
Storage pool new Unchecked_Deallocation, या controlled types और containers Access types से आगे

Diagram में solid line हमेशा लागू रहने वाला relation दिखाती है और dashed line conditional relation दिखाती है (शर्तें detail page पर हर relation के explanation में दी गई हैं)। Relations की पूरी list (कुल 15, evidence और certainty सहित) तथा मुख्य concepts की definitions knowledge map की detail page पर संकलित हैं (जापानी में)। Data: JSON-LD / Turtle

Unknown length की values new के बिना return करना

C में runtime पर तय होने वाली length की string return करने के लिए आम तौर पर या तो caller से buffer तैयार करवाया जाता है, या function के अंदर malloc करके caller से free करवाया जाता है। Ada में unknown length वाली String को सीधे return value बनाया जा सकता है।

with Ada.Text_IO; use Ada.Text_IO;

procedure Repeat_Demo is
   --  Return value की length call होने तक तय नहीं होती
   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 लिखा है, न deallocation। Line की length इस बात से तय होती है कि Repeat क्या return करता है। इस program को valgrind में चलाने पर heap allocation शून्य बार हुआ।

इस article के environment वाला GNAT ऐसी return values को secondary stack पर रखता है। GNAT binder की documentation secondary stack को “functions द्वारा return किए गए unconstrained types के objects (जैसे unconstrained String) रखने की जगह” बताती है3। कई environments में secondary stack ज़रूरत के हिसाब से बढ़ता है और heap पर blocks की chain के रूप में implement होता है3। GNAT documentation यह भी कहती है कि function return values के लिए secondary stack सिर्फ़ कुछ targets पर इस्तेमाल होता है4।

Block से निकलने के बाद memory दोबारा इस्तेमाल होती है या नहीं, यह 1 MB की string 10,000 बार return करने वाले loop से check किया।

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 की string 10,000 बार return करें, कुल लगभग 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 की strings return करने के बाद भी heap allocation सिर्फ़ एक बार, 1,000,048 bytes का हुआ। यह एक allocation शायद secondary stack को बढ़ाने वाला block है; उसके बाद की iterations में कोई नया allocation नहीं हुआ। new से बनी values की तरह program को deallocation लिखने की ज़रूरत नहीं पड़ती।

Secondary stack कैसे इस्तेमाल होता हैFunction unknown length की value return करे, तो वह secondary stack पर push होती है, caller के block में इस्तेमाल होती है और block से निकलने पर release होती है, यह दिखाता है।Repeat को call करेंResult को secondary stack पर push करेंdeclare block में Line के रूप में इस्तेमाल करेंBlock से निकलेंPush की गई memory release करें

चित्र 2: Unknown length की return value caller के block से निकलते ही release हो जाती है।

GNAT का यह इस्तेमाल pragma Restrictions (No_Secondary_Stack) लगाकर confirm किया जा सकता है। यह restriction compile time पर guarantee करता है कि generated code secondary stack को refer नहीं करता4। ऊपर वाले Repeat जैसा ही function इस restriction के साथ compile करने पर ये errors आए।

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

इस restriction वाले code में caller तय length का array तैयार करता है और function उसमें लिखता है।

Access types से तय करना कि “क्या point कर सकते हैं”

Heap की ज़रूरत तब पड़ती है जब बनाई गई value को उसके scope के बाहर भी इस्तेमाल करना हो, या list या tree की तरह elements को आपस में जोड़ना हो। Ada में इसके लिए access types इस्तेमाल होते हैं। Access type C के pointer जैसा है, लेकिन वह क्या point कर सकता है, यह type declaration तय करता है2।

Pool-specific और general access types

सिर्फ़ access से declare किया गया type pool-specific access type है। वह सिर्फ़ उसी type के new से बनी values (उसके storage pool के elements) को point कर सकता है। access all से declare किया गया type general access type है, और वह aliased के साथ declare किए गए variables को भी point कर सकता है2।

with Ada.Text_IO; use Ada.Text_IO;

procedure Access_Kinds is
   --  Pool-specific access type: सिर्फ़ new से allocate हुई चीज़ को point कर सकता है
   type Int_Ptr is access Integer;

   --  General access type: aliased variables को भी point कर सकता है
   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

उल्टे combinations compile error देते हैं: pool-specific type से किसी variable को point करना, और aliased के बिना वाले variable को point करना।

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;  --  Pool-specific type किसी variable को point नहीं कर सकता
   R1 : Int_Ref := Plain'Access;    --  जो variable aliased नहीं है उसे point नहीं कर सकते
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

इस rule की वजह से declarations पढ़कर ही पता चल जाता है कि किन variables को pointer से point किया जा सकता है।

Access types के प्रकार और वे क्या point कर सकते हैंPool-specific access type सिर्फ़ new से बनी values को point करता है, और general access type new से बनी values के साथ aliased declare किए गए variables को भी point कर सकता है, यह दिखाता है।Pool-specific access type (access)new से बनी valuesGeneral access type (access all)aliased declare किए गए variablesaliased के बिना variablesकोई access type उन्हें point नहीं कर सकता

चित्र 3: सिर्फ़ general access types ही aliased declare किए गए variables को point कर सकते हैं।

Lifetime check (accessibility check)

C में एक आम गलती यह है कि function के local variable का address ऐसी जगह store कर दिया जाए जो function return होने के बाद भी बची रहती है। Ada इसे accessibility checks से रोकता है। अगर किसी variable की lifetime (accessibility level) access type की lifetime से छोटी है, तो उस variable को point करने वाली value उस type में store नहीं की जा सकती5।

Compile time पर पता चल सके, तो यह compile error होता है। नीचे का package library level वाले variable Saved (जो program के अंत तक रहता है) में parameter variable को point करने वाली value store करने की कोशिश करता है।

package Registry is
   type Int_Ref is access all Integer;

   Saved : Int_Ref;  --  Library-level variable; program के अंत तक रहता है

   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

अगर parameter anonymous access type (access Integer) का हो, तो caller क्या pass करेगा यह compile time पर पता नहीं होता। ऐसे में check runtime पर होता है, और fail होने पर Program_Error raise होता है5।

package Registry is
   type Int_Ref is access all Integer;

   Saved : Int_Ref;  --  Library-level variable; program के अंत तक रहता है

   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);  --  Actual parameter की lifetime runtime पर check होती है
   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

Library level वाला Global_Value pass करने पर store हो गया, और Try_Local का local variable pass करने पर store करते समय ही रुक गया। C में यही करने पर store हो जाता है, और function return होने के बाद उस value को इस्तेमाल करना undefined behavior है। Ada में यह उसी line पर रुक जाता है जो store करने की कोशिश करती है।

Accessibility check कब होता हैछोटी lifetime वाले variable को point करने वाली value को लंबी lifetime वाले access type में store करने की कोशिश, compile time पर पता चले तो compile error होती है, और anonymous access type parameter की तरह runtime तक पता न चले तो Program_Error होता है, यह दिखाता है।हाँनहीं (anonymous access type parameter)छोटी lifetime वाले variable को point करने वाली value store करेंक्या lifetime compile time पर पता हैCompile errorRuntime पर checkProgram_Error

चित्र 4: Lifetime check जहाँ संभव हो compile time पर, नहीं तो runtime पर होता है।

Null न allow करने वाले access types

Access type का variable initial value न देने पर null होता है। Parameter या variable के type में not null जोड़ने पर वह type null को exclude कर देता है2। null pass करने पर call के point पर ही Constraint_Error आता है।

with Ada.Text_IO; use Ada.Text_IO;

procedure Not_Null_Demo is
   type Int_Ptr is access Integer;

   --  Type खुद promise करता है कि parameter कभी 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;  --  Initial value के बिना access variable 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

पहला compile time का warning है, दूसरा runtime का output। Show के अंदर null check करने की ज़रूरत नहीं रही, और null pass होने पर error Show के अंदर नहीं, बल्कि call करने वाली line (line 16) पर report होता है।

Unchecked_Deallocation से free करना

new से allocate हुई value को Ada.Unchecked_Deallocation को instantiate करके बने procedure से free किया जाता है। Convention के हिसाब से इस procedure का नाम Free रखा जाता है। RM के rules के मुताबिक Free (X) के बाद X null हो जाता है, और अगर X पहले से null है तो कुछ नहीं होता6।

नाम में Unchecked है, उसी के मुताबिक यह procedure उसी memory को point करने वाले दूसरे pointers को नहीं देखता। नीचे के example में A और B एक ही value को point कर रहे हैं, और उसी हालत में A को free किया गया है।

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;  --  उसी object को point करने वाला दूसरा pointer
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));  --  Free हो चुकी memory पढ़ें
end Dangling_Demo;
A = null : TRUE
B = null : FALSE
B.all    = 1613378576

A null हो गया, लेकिन B के पास अब भी पुराना address है। जो value ऐसे object को point करे जो अब मौजूद नहीं है, उसे RM dangling reference कहता है, और उसे dereference करने वाले execution को erroneous (result standard से तय नहीं) मानता है6। GNAT 13.3 में कोई exception नहीं आया, और B.all ने 42 के अलावा कोई और value return की। यही program valgrind में चलाने पर report आता है कि freed memory पढ़ी गई।

==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)

इस trace से यह भी दिखता है कि GNAT का default pool __gnat_free के ज़रिए C का free call करता है।

Unchecked_Deallocation के बाद बचा रह जाने वाला pointerFree(A) से A null हो जाता है, लेकिन उसी memory को point करने वाला B पुराना address रखे रहता है, B को dereference करना erroneous है, और valgrind इसे freed memory के read के रूप में report करता है, यह दिखाता है।A और B एक ही value को point करते हैंFree (A)A null हो जाता हैB पुराना address रखे रहता हैB.all पढ़ेंErroneous (result तय नहीं)valgrind: Invalid read

चित्र 5: Free सिर्फ़ pass किए गए variable को null करता है; उसी memory को point करने वाले दूसरे variables बने रहते हैं।

उल्टा, अगर free न करें तो memory वापस नहीं मिलती। नीचे का loop उसी variable में 1,000 बार new का result रखता है, और हर बार पिछली value का pointer खो देता है।

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);  --  पिछली memory का pointer यहाँ खो जाता है
   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 वाली language जो memory reclaim कर लेती, वह GNAT में program के अंत तक allocated रही। GNAT documentation भी कहती है कि default pool (System.Pool_Global) malloc और free इस्तेमाल करता है और memory को अपने-आप reclaim नहीं करता1।

Standard भी GC मानकर नहीं चलता। Ada 2012 revision में Reference Manual से garbage collection से जुड़ा text हटा दिया गया। Annotated Reference Manual (AARM) के मुताबिक इसके बदले Ada 2012 subpools देता है, जो GC से कहीं ज़्यादा predictable हैं7।

SPARK के ownership rules

Ada का subset SPARK access types पर ownership rules लागू करता है। Allocate हुई memory को read और write कर सकने वाली access value एक समय में सिर्फ़ एक होती है8। पहले वाले Dangling_Demo जैसा ही sequence SPARK code के रूप में लिखा, और GNATprove 15.1 से --mode=check_all के साथ check किया।

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 की ownership B पर move होती है
   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 की ownership B पर move होती है
      |                  ^ here

B := A पर ownership B पर move हो जाती है, इसलिए A को free करने वाली line पर check ने रोक दिया। GNAT से compile और run किए गए Dangling_Demo में यही गलती कोई exception नहीं देती थी, और सिर्फ़ valgrind से पकड़ में आई। SPARK में proof कैसे आगे बढ़ाएँ, यह “Proving AI-Written Code with SPARK” (English) में बताया गया है।

एक ही गलती को Ada और SPARK कैसे handle करते हैंदो pointers से एक ही memory को point करके एक को free करने की गलती, Ada के रूप में चलाने पर पकड़ में नहीं आती और freed memory पढ़ी जाती है, जबकि SPARK के रूप में check करने पर GNATprove ownership move होने की वजह से error देता है, यह दिखाता है।दो pointers से एक ही memory point करके free करेंAda के रूप में run करेंSPARK के रूप में check करेंबिना पकड़े freed memory पढ़ता हैGNATprove ownership move की वजह से error देता है

चित्र 6: SPARK में वही गलती ownership rules की वजह से check के stage पर ही पकड़ी जाती है।

Plain Ada में लिखते समय Free call करने वाली जगहों को उन कुछ spots तक सीमित रखें जहाँ साफ़ हो कि value का owner कौन है। इसका मुख्य उदाहरण नीचे के controlled types हैं।

Controlled types से scope से निकलते समय cleanup

Ada.Finalization के Controlled type से derive करने पर तीन procedures override किए जा सकते हैं9।

Procedure कब call होता है
Initialize जब object initial value के बिना declare होता है
Adjust Assignment से copy होने के बाद, copy के target पर
Finalize Scope से निकलते समय, assignment से overwrite होने से पहले, और Free से deallocate होने पर

ये किस क्रम में call होते हैं, यह check करने के लिए एक type बनाया जो हर call पर अपना नाम print करता है। Adjust में नाम को lowercase कर दिया ताकि पता चले कि कौन-सा object copy है।

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;

   --  नाम lowercase करें, ताकि पता चले कि यह copy है
   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
      --  Initial value नहीं है, इसलिए Initialize call होता है
      A : Resource;
      --  Aggregate से initialize है, इसलिए Initialize call नहीं होता
      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

Output से ये बातें दिखती हैं:

  • Initialize सिर्फ़ A के लिए call हुआ, जिसकी initial value नहीं थी, और aggregate से initialize हुए B के लिए नहीं। RM भी कहता है कि Initialize default initialization पर call होता है9।
  • B := A पर पहले overwrite होने वाले B का Finalize, फिर copy हुई value का Adjust call हुआ।
  • Block से निकलते समय Finalize declaration के उल्टे क्रम में (B की copy, फिर A) call हुआ।
  • Exception से block से निकले C के लिए भी Finalize call हुआ।
Controlled type के procedures किस क्रम में call होते हैंInitial value के बिना declaration पर Initialize, assignment पर overwrite होने वाले side का Finalize और copy का Adjust, और scope से निकलने या exception से बाहर जाने पर declaration के उल्टे क्रम में Finalize call होता है, यह दिखाता है।Initial value के बिना declare करेंInitializeB := A execute करेंB की पुरानी value का FinalizeCopy हुई value का AdjustScope से निकलें या exception से बाहर जाएँDeclaration के उल्टे क्रम में Finalize

चित्र 7: Assignment पर पुरानी value का Finalize और copy का Adjust, और scope से निकलने पर उल्टे क्रम में Finalize call होता है।

Exception से निकलने पर भी Finalize call होता है, इसलिए heap का deallocation यहाँ लिख दें तो caller Free लिखना भूल ही नहीं सकता। यह C++ के RAII वाला ही idea है, जहाँ deallocation destructor में लिखा जाता है। C++ वाले RAII की बात “Practical multithreading best practices: C++ संस्करण” में है।

जिन resources को copy नहीं होने देना है, उनके लिए Limited_Controlled इस्तेमाल करें। इससे ऐसा type बनता है जिसे assign नहीं किया जा सकता, इसलिए उसमें Adjust नहीं होता। अगले section का example इसी को इस्तेमाल करता है।

Storage pools से तय करना कि memory कहाँ से आए

new memory कहाँ से लेता है, यह हर access type के storage pool से तय होता है। कुछ specify न करें तो implementation का default pool इस्तेमाल होता है; GNAT में वह System.Pool_Global है, जो malloc और free इस्तेमाल करता है1। Ada में यह pool हर type के लिए बदला जा सकता है या उस पर limit लगाई जा सकती है10।

Storage_Size से limit लगाना

किसी access type के लिए Storage_Size specify करने पर उस type का new implementation-defined pool से allocate करता है, जिसमें कम से कम specify की गई memory होती है। वह memory खत्म होने पर और allocation नहीं होता और Storage_Error raise होता है10।

with Ada.Text_IO; use Ada.Text_IO;

procedure Bounded_Demo is
   --  इस type के new के लिए उपलब्ध memory 64 bytes तक सीमित करें
   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 allocations के बाद 9वाँ new Storage_Error दे गया। एक allocation कितनी memory लेता है, यह implementation तय करता है, इसलिए count को सिर्फ़ Integer के size से नहीं निकाला जा सकता। इस pool की memory उस scope से निकलते समय reclaim हो जाती है जहाँ access type declare हुआ था10। जब हर type का memory usage capped रखना हो, जैसे fixed memory limit वाले embedded devices में या लंबे समय तक चलने वाले processes में, तब यह काम आता है।

Storage_Size specify किए गए access type से allocationStorage_Size specify किए गए access type से new execute करने पर pool में जगह हो तो allocate होता है, खत्म हो गई हो तो Storage_Error आता है, और access type declare करने वाले scope से निकलने पर pool की memory reclaim होती है, यह दिखाता है।हाँनहींInt_Ptr से new execute करेंक्या pool में खाली जगह हैAllocate करेंStorage_ErrorAccess type declare करने वाले scope से निकलेंPool की memory reclaim करें

चित्र 8: Storage_Size वाला type budget खत्म होने पर Storage_Error देता है, और scope से निकलने पर पूरा budget reclaim हो जाता है।

अपना pool लिखना

System.Storage_Pools के Root_Storage_Pool से derive करके और Allocate, Deallocate और Storage_Size override करके अपना pool बनाया जा सकता है10। नीचे का pool allocations, deallocations और इस्तेमाल में bytes गिनता है, और असली allocation GNAT के default pool पर छोड़ देता है। System.Pool_Global GNAT-specific unit है, इसलिए दूसरे implementations में allocation के लिए कोई और जगह चाहिए।

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

package Counting_Pools is
   --  Allocations, deallocations और इस्तेमाल में bytes गिनने वाला pool
   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 का default pool (GNAT-specific unit)

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;  --  कोई upper limit नहीं
   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;

इस pool को पिछले section के Limited_Controlled के साथ जोड़ते हैं। Buffer ऐसा type है जो heap पर ठीक एक array रखता है और Finalize में उसे free करता है। Access type Byte_Array_Ptr के लिए Storage_Pool => Pool specify किया है, ताकि इस type का 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;

   --  Heap पर ठीक एक array रखने वाला और scope से निकलते समय उसे free करने वाला type
   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 bytes लौटाकर फिर से 50 bytes लें
      Report (Pool, "in block   ");
   end;  --  X और Y का Finalize बाकी memory free करता है

   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

Block के अंदर 3 allocations और 1 deallocation हुआ, और block से निकलने के बाद allocations और deallocations की गिनती बराबर हो गई और usage वापस 0 पर आ गया। Pool_Demo एक बार भी Free call नहीं करता। Deallocation सिर्फ़ Allocate के अंदर दोबारा लेने पर और Buffer के Finalize में होता है। valgrind के --leak-check=full ने भी इस program के लिए कुछ report नहीं किया।

इस्तेमाल में 268 bytes, elements की कुल संख्या (250) से ज़्यादा है। Allocate को pass हुआ हर size print करने पर 108, 208 और 60 bytes निकले। Element count से ज़्यादा वाले हिस्से में शायद array के index bounds रखने की जगह वगैरह शामिल है, लेकिन breakdown implementation तय करता है और इस article में verify नहीं किया गया।

Counting pool से होकर allocation और deallocationBuffer type के new और Free, access type के लिए specify किए गए Counting_Pool के Allocate और Deallocate को call करते हैं, और Counting_Pool गिनती करके allocation और deallocation GNAT के default pool पर छोड़ देता है, यह दिखाता है।Buffer के अंदर newCounting_Pool का AllocateFinalize में FreeCounting_Pool का DeallocateCalls और usage गिनेंGNAT का default poolmalloc और free

चित्र 9: Access type के लिए pool specify करने पर उस type का हर new और Free उसी pool से होकर जाता है।

इस तरह allocations गिनने वाला pool tests में यह check करने के लिए इस्तेमाल हो सकता है कि “operation के बाद usage 0 पर लौटता है या नहीं”। GNAT में GNAT.Debug_Pools भी है, जो freed memory के references जैसी चीज़ें detect करता है11। इस article में इसे try नहीं किया गया।

Subpools

Ada 2012 में System.Storage_Pools.Subpools जोड़ा गया, जो एक pool को कई subpools में बाँटता है12। new (Subpool) T की तरह allocate करने वाला subpool specify किया जा सकता है, और पूरे subpool को एक साथ free किया जा सकता है। यह ऐसे इस्तेमाल के लिए ठीक है जहाँ processing की हर unit के लिए allocate हुई values को अंत में एक साथ फेंक दिया जाए। इस article में subpool का कोई example run नहीं किया गया।

Standard containers से hand-written pointers कम करना

Access types और controlled types को मिलाकर safe types बनाए जा सकते हैं, लेकिन हर variable-length sequence या dictionary के लिए खुद लिखने की ज़रूरत नहीं है। Ada 2005 से उपलब्ध Ada.Containers में vectors, lists, maps, sets वगैरह हैं13, और elements का allocation और deallocation containers खुद करते हैं।

जिन elements का size हर value के साथ बदलता है, जैसे अलग-अलग length की String, उन्हें नाम में Indefinite_ वाले containers में रखें।

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

procedure Containers_Demo is
   --  अलग-अलग length की String सीधे elements बन सकती हैं
   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

इस program में न new है न Free। valgrind में चलाने पर exit के समय usage 0 bytes था, और allocate हुआ हर block free हो चुका था।

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

Containers generic packages हैं, इसलिए element type pass करके उन्हें instantiate किया जाता है। Generics कैसे काम करते हैं, यह “Ada में generic programming” में समझाया गया है।

कौन-सा mechanism चुनें: rules of thumb

अब तक के mechanisms को ऊपर से क्रम में सोचें, तो चुनना आसान हो जाता है।

Ada में memory handle करने का तरीका चुनने का क्रमपहले देखें कि क्या value के रूप में declare किया जा सकता है; elements जोड़ने-हटाने हों तो containers; custom structure चाहिए तो access types और controlled types; और memory कहाँ से आए या limit तय करनी हो तो storage pools, यह सोचने का क्रम दिखाता है।हाँनहींहाँनहींहाँक्या value के रूप में declare और return हो सकता हैVariable या return value के रूप में ही रखेंक्या sequence या dictionary काफ़ी हैAda.ContainersAccess types और controlled typesक्या memory का source या limit तय करना हैStorage pools

चित्र 10: Value के रूप में handle न हो सके तो containers, और वे भी काफ़ी न हों तो access types और controlled types पर विचार करें।

  • अगर दिक्कत सिर्फ़ इतनी है कि length runtime पर तय होती है, तो value के रूप में declare करें और functions से return करें। new की ज़रूरत नहीं।
  • Elements जोड़ने और हटाने हों, तो Ada.Containers इस्तेमाल करें।
  • Tree या graph जैसा custom structure चाहिए, तो उसे access types से बनाएँ, और Free call करने वाली जगहें controlled type के Finalize जैसी कुछ जगहों तक सीमित रखें। aliased और not null से type में लिख दें कि क्या point हो सकता है और null allowed है या नहीं।
  • Allocation की limit या memory का source तय करना हो, तो Storage_Size या storage pool specify करें।

Ada के types memory का इस्तेमाल express करें, तब भी compiler Unchecked_Deallocation के गलत इस्तेमाल को रोकने तक नहीं जाता। उस हिस्से को छोटा रखें, और बाकी जगहें valgrind या counting pool से check करें। जिन हिस्सों में ownership rules भी check करवाने हों, उन्हें SPARK में लिखने का विकल्प भी है।

.NET जैसे GC वाले environment में बढ़ती memory को कैसे investigate करें, यह “.NET में GC wait और memory leak कैसे अलग करें” में है।

संबंधित लेख

संदर्भ

  1. GNAT Reference Manual, System.Pool_Global (s-pooglo.ads). Default storage pool जैसा ही pool, जो malloc और free इस्तेमाल करता है और automatic reclamation नहीं करता। ↩ ↩2 ↩3

  2. Ada Reference Manual (Ada 2022), 3.10 Access Types. Pool-specific और general access types, aliased, और null exclusion (not null)। ↩ ↩2 ↩3 ↩4

  3. GNAT User’s Guide, Switches for gnatbind. -D switch के description में secondary stack की भूमिका और implementation। ↩ ↩2

  4. GNAT Reference Manual, No_Secondary_Stack. ऐसा restriction जो compile time पर guarantee करता है कि generated code secondary stack को refer नहीं करता। ↩ ↩2

  5. Ada Reference Manual (Ada 2022), 3.10.2 Operations of Access Types. Accessibility levels, और check fail होने पर Program_Error। ↩ ↩2

  6. Ada Reference Manual (Ada 2022), 13.11.2 Unchecked Storage Deallocation. Free (X) के बाद X का null होना, dangling references, और erroneous execution। ↩ ↩2

  7. Annotated Ada Reference Manual (Ada 2022), 13.11.3 Default Storage Pools. “Wording Changes from Ada 2005” के अंतर्गत 9.d/3: Ada 2012 ने garbage collection का text हटाया और subpools दिए। ↩

  8. AdaCore, SPARK User’s Guide, Language Restrictions. Access types और allocators ownership rules follow करते हैं, और allocate हुई memory को एक समय में सिर्फ़ एक access value read और write कर सकती है (Memory Ownership Policy)। ↩

  9. Ada Reference Manual (Ada 2022), 7.6 Assignment and Finalization. Controlled और Limited_Controlled, Initialize, Adjust और Finalize किन conditions में call होते हैं, और assignment के steps। ↩ ↩2

  10. Ada Reference Manual (Ada 2022), 13.11 Storage Management. Root_Storage_Pool और Allocate, Deallocate, Storage_Size; Storage_Size specify किए गए type का pool, और Storage_Error। ↩ ↩2 ↩3 ↩4

  11. GNAT User’s Guide, The GNAT Debug Pool Facility. GNAT.Debug_Pools, जो हर dereference पर check करता है कि pointer ठीक से allocate हुई memory को point करता है। ↩

  12. Ada Reference Manual (Ada 2022), 13.11.4 Storage Subpools. System.Storage_Pools.Subpools से subpools। ↩

  13. Ada Reference Manual (Ada 2022), A.18 Containers. Ada.Containers के vectors, lists, maps और sets, और नाम में Indefinite_ वाले containers। ↩

निकटवर्ती विषयों में गहराई से जाने के लिए समान टैग वाले नवीनतम लेख।

ये इस विषय से जुड़े topic पृष्ठ हैं। लेख से शुरू करके आप संबंधित सेवाओं और दूसरे लेखों तक जा सकते हैं।

यह लेख नीचे दिए गए सेवा पृष्ठों से जुड़ता है। जो प्रवेश-बिंदु आपके सबसे क़रीब हो, वहाँ से देखिए।

तकनीकी परामर्श और डिज़ाइन समीक्षा

Ada या C में लिखे control या embedded code में कौन-सी values heap पर रहें, और कौन उन्हें कब free करे, इसका design दोबारा करना हो, तो इसे technical consulting और design review के रूप में ले सकते हैं।

त्रुटि जाँच और मूल कारण विश्लेषण

लंबे समय तक चलाने पर memory बढ़ती जाती है, या पहले से free किया गया area पढ़ने से values खराब हो जाती हैं, ऐसे symptoms की वजह ढूँढना bug investigation और root-cause analysis के लिए अच्छा विषय है।

अक्सर पूछे जाने वाले प्रश्न

इस लेख के विषय पर परामर्श में अक्सर पूछे जाने वाले प्रश्न।

क्या Ada में garbage collection है?
GNAT का default storage pool malloc और free से allocate और deallocate करता है, और इस्तेमाल न होने वाली memory को अपने-आप reclaim नहीं करता। Ada 2012 revision में Reference Manual से garbage collection से जुड़ा text हटा दिया गया, और ज़्यादा predictable mechanism के रूप में subpools जोड़े गए। Deallocation Unchecked_Deallocation से करें, या इसे controlled types या standard containers पर छोड़ दें।
जो function runtime पर तय होने वाली length की string return करता है, क्या वह heap इस्तेमाल करता है?
new लिखे बिना भी return किया जा सकता है। Target के हिसाब से GNAT, unknown length वाले arrays या records return करने वाले functions के लिए secondary stack इस्तेमाल करता है। Linux x86_64 पर GNAT 13.3 में 1 MB की string 10,000 बार return करने पर भी heap allocation लगभग 1 MB का सिर्फ़ एक बार हुआ। pragma Restrictions (No_Secondary_Stack) लगाने पर ऐसा इस्तेमाल compile error बन जाता है।
Unchecked_Deallocation से free करने के बाद उसी area को point करने वाले दूसरे pointer का क्या होता है?
Deallocation को pass किया गया variable null हो जाता है, लेकिन उसी area को point करने वाले दूसरे variables पुराना address रखे रहते हैं। उन्हें dereference करने पर execution erroneous हो जाता है (result standard से तय नहीं होता)। GNAT 13.3 में try करने पर कोई exception नहीं आया, और valgrind ने इसे freed memory के read के रूप में report किया।
क्या Ada में C++ के RAII जैसा कुछ है?
हाँ: Ada.Finalization के Controlled और Limited_Controlled types। Finalize को override करने पर यह scope से निकलते समय call होता है, exception से बाहर निकलने पर भी। Heap का deallocation वहाँ लिख दें, तो caller को deallocation लिखने की ज़रूरत नहीं पड़ती।

लेखक की प्रोफ़ाइल

लेख के लेखक का परिचय पृष्ठ।

Go Komura

KomuraSoft LLC के प्रतिनिधि

Windows सॉफ़्टवेयर विकास, तकनीकी परामर्श और बग जाँच पर केंद्रित; जिन परियोजनाओं में मौजूदा assets बचे हैं, उनमें और जिन खराबियों का कारण आसानी से नहीं दिखता, उनकी जाँच में हमारी विशेष ताकत है।

सार्वजनिक लिंक

ब्लॉग पर लौटें