While doing advent of code challenges and making sure the solutions do not make any heap allocations during run-time except for application start up (elaboration time), I’ve discovered that opening a file with Ada.Text_IO.Open (…) generates a heap allocation. It means that if one does not closes the file, either deliberately or by mistake due to raising of an exception not only would make an application leak file handles but also memory.
One may wonder about why this is so. I did not expect a heap allocation opening a file. Maybe this is applies only to the implementation of the standard library Ada.Text_IO package of the GNAT compiler, but not for example to the Ada.Streams.Stream_IO package (I haven’t checked!). One reason that I can imagine is usage of Taft Types (Opaque types). It means a File_Type is defined in the public part of the specification package of Text_IO but the exact details of File_Type is defined in the body of the Text_IO package. It is smart because one only needs to replace the body of Text_IO package when porting the standard library to another platform or operating system. The down side is that Taft Types, introduced in Ada83, is closely connected with heap allocations (my experience is that it is hard to avoid heap allocations when using Taft Types).
Any other reason for making heap allocation when opening file?
5 posts - 4 participants