Convert from System.Address to Integer in Ada - memory-management

In the example below, I am wondering, why line 17 does not work, but line 18? Can I not convert a System.Address directly to an Integer (see line 17)?
main.adb
with Ada.Text_IO;
with Ada.Unchecked_Conversion;
with System.Storage_Elements;
procedure Main is
package SSE renames System.Storage_Elements;
type Integer_Access is access Integer;
I1_Access : Integer_Access := new Integer'(42);
I1_Address : System.Address := I1_Access.all'Address;
function Convert1 is new Ada.Unchecked_Conversion (System.Address, Integer);
function Convert2 is new Ada.Unchecked_Conversion (System.Address, Integer_Access);
begin
Ada.Text_IO.Put_Line (SSE.To_Integer (I1_Access'Address)'Img);
Ada.Text_IO.Put_Line (SSE.To_Integer (I1_Access.all'Address)'Img);
Ada.Text_IO.Put_Line (I1_Access.all'Img);
Ada.Text_IO.Put_Line (Convert1 (I1_Address)'Img); -- why does this NOT work?
Ada.Text_IO.Put_Line (Convert2 (I1_Address).all'Img); -- why does this work?
end Main;
Result
140734773254664
140243203260416
42
-363855872
42

If I compile your code on this Mac with -gnatwa (most warnings) and -gnatl (generate a listing) I get (excerpted)
12. function Convert1 is new Ada.Unchecked_Conversion (System.Address, Integer);
|
>>> warning: types for unchecked conversion have different sizes
because Integer is 32-bits while System.Address (and most access types) are 64-bits. Your machine is evidently similar.
So the reason you get a weird 5th output line (I got -490720512, by the way) is that it’s only looking at the bottom 32 bits of the actual address.
You might look at System.Address_To_Access_Conversions (ARM 13.7.2) for the supported way to do this.

It does work. Apparently it's doing something other than what you expected.
You can convert a System.Address to an Integer using Unchecked_Conversion, but the result isn't necessarily going to be meaningful. You'll get an integer representing the (probably virtual) address held in the System.Address value -- not the value of whatever object it points to. And if System.Address and Integer aren't the same size, the result will be even less meaningful.
Ada.Text_IO.Put_Line (Convert1 (I1_Address)'Img);
This prints an Integer representation of a memory address. It's not particularly meaningful. (Typically you'd want to see such an address in hexadecimal.)
Ada.Text_IO.Put_Line (Convert2 (I1_Address).all'Img);
This prints the Integer value, 42, of the object at the memory location indicated by the value of I1_Address. It's just a roundabout way of printing I1_Access.all.

If you only want to print the value of an image, as in your example, consider using the function System.Address_Image. This is not good for pointer arithmetic, but leads to better output (hexadecimal, for instance)

Related

What can make the output of a simple ada program indent, when not told to?

I am currently doing the Ada tutorial from learn.adacore.com, and I am now at the second example: reading and outputting an integer. Since copy-pasting is for people who don't want to learn the syntax, I manually typed out most of the code (Some of it was generated by gnat-gps, but I'm now using vim).
I compiled and ran the program, and surprisingly, the second line of output is indented by roughly one tab. Why?
Here's the code:
With Ada.Text_IO;
Use Ada.Text_IO;
With Ada.Integer_Text_IO;
use Ada.Integer_Text_IO;
procedure Main is
N : Integer;
begin
-- Insert code here.
Put("Enter an integer value: ");
Get(N);
if N>0 then
Put (N);
Put_Line(" is a positive number");
end if;
end Main;
(how do I get syntax highlighting?)
Here is a sample of the output (the first 1 being input):
Enter an integer value: 1
1 is a positive number
The Put procedure from Ada.Integer_Text_IO uses a default field width padded with spaces.
The specification for that procedure is defined in the Ada Language Reference Manual as:
procedure Put(Item : in Num;
Width : in Field := Default_Width;
Base : in Number_Base := Default_Base);
The Width and Base parameters are given default values. Your call to Put only supplied a value for the formal parameter Item. To eliminate the left padding simply specify a desired width. I suggest you use Ada named notation for the call as in
Put(Item => N, Width => 1);

Ada random numbers are identical

I have following problem with my function which should return a random numer. When I want to generate a couple of numbers by calling that function, they are exactly the same. How can I fix the problem of returning the same number all the time when I call the function? I need that random to keep in function.
Here is the code:
with Ada.Numerics.discrete_Random
function generate_random_number ( n: in Positive) return Integer is
subtype Rand_Range is Integer range 0 .. n;
package Rand_Int is new Ada.Numerics.Discrete_Random(Rand_Range);
use Rand_Int;
gen : Rand_Int.Generator;
ret_val: Rand_Range;
begin
Rand_Int.Reset(gen);
ret_val := Random(gen);
return ret_val;
end;
The random generator gen should not be local to the function. Currently you are creating it anew on each generate_random_number call, and initialising it, so it's not surprising you always get the same result.
If you make gen - for instance - a global variable, initialised once, then each time you use it you'll get a new random number. (Yes, global variables are bad : but see below)
Unfortunately this does not play particularly well with the semantics of function generate_random_number ( n: in Positive) which can restrict the range of the random number differently each time. The simplest solution is to make gen return any valid integer and use modular arithmetic to return a number in the correct range for each call. This will work but you should be aware that it potentially introduces cryptographic weaknesses, beyond my skills to analyze.
If that is the case you will need a different approach, for example creating a different random generator for each range you need; taking care to seed (reset) them differently otherwise there may again be crypto weaknesses such as correlations between different generators.
Now global variables are poor structure for all the usual reasons in any language. So a much better way is to make it a resource by wrapping it in a package.
package RandGen is
function generate_random_number ( n: in Positive) return Positive;
end RandGen;
And that is all the client needs to see. The package is implemented as follows:
with Ada.Numerics.discrete_Random;
package body RandGen is
subtype Rand_Range is Positive;
package Rand_Int is new Ada.Numerics.Discrete_Random(Rand_Range);
gen : Rand_Int.Generator;
function generate_random_number ( n: in Positive) return Integer is
begin
return Rand_Int.Random(gen) mod n; -- or mod n+1 to include the end value
end generate_random_number;
-- package initialisation part
begin
Rand_Int.Reset(gen);
end RandGen;
EDIT : Jacob's suggestion of rejecting out-of-range values is better but inefficient if n is much smaller than the generator range. One solution might be to create several generators and let the generate_random_number function choose the one which covers 0 .. N with least waste.
The Random procedure with only one parameter is supposed to initiate the random number generator with a "time-dependent state". However, if it is called more than once rapidly in succession, it is very likely that the "time" that the program uses will be the same each time, since the program is likely to run faster than the clock resolution. (Try your test with something like delay 0.5 in between the two uses of generate_random_number; most likely you will get two different results.)
In any event, the intended use of a random number generator is to use Reset on it once to set the seed, and then generate a sequence of random numbers starting with the seed. By doing this, you can also use the same seed every time in order to get a duplicatable sequence of random numbers, for testing; or you can use a time-dependent seed. However, resetting the random number generator every time you want a random number is not the normal or recommended way of using RNG's. Therefore, you need to move the Reset call out of generate_random_number. Unfortunately, this also means that you have to use the same generator even if the n parameter will be different on every call, which means you may be forced to use Float_Random instead of Discrete_Random.
P.S. Looking into it further, I found this in G.2.5: "Two different calls to the time-dependent Reset procedure shall reset the generator to different states, provided that the calls are separated in time by at least one second and not more than fifty years." [Emphasis mine.] I'm sure that when you tried it, the calls were less than one second apart.
Assuming that the upper limit can be determined when you start the program:
Package Random (specification):
with Generic_Random;
with Upper_Limit_Function;
package Random is new Generic_Random (Upper_Limit => Upper_Limit_Function);
Generic package Generic_Random (specification):
generic
Upper_Limit : Positive;
package Generic_Random is
subtype Values is Natural range 0 .. Upper_Limit;
function Value return Values;
end Generic_Random;
Generic package Generic_Random (body):
with Ada.Numerics.Discrete_Random;
package body Generic_Random is
package Random is new Ada.Numerics.Discrete_Random (Values);
Source : Random.Generator;
function Value return Values is
begin
return Random.Random (Source);
end Value;
begin
Random.Reset (Source);
end Generic_Random;

My sorting algorithm runtime errors

I developed the following sorting algorithm but there are some run time errors that I cant figure out. The program terminates when it comes to the part of filling the array. I'm still a beginner in ada so I couldn't figure out where the problem is...
With Ada.Text_IO;
With Ada.Integer_Text_IO;
Use Ada.Integer_Text_IO;
Use Ada.Text_IO;
Procedure sort is
n,i,x : Integer;
-- Max_Heapify Function...
Procedure Max_Heapify ( i, n : integer) is
j, Temp : Integer;
begin
Temp:=Int_Acc(i);
j:=2*i;
if Temp>Int_Acc(j) then
elsif Temp<=Int_Acc(j) then
Int_Acc(j/2):=Int_Acc(j);
j:=2*j;
end if;
end loop;
Int_Acc(j/2):=Temp;
end Max_Heapify;
begin
Get(n);
for i in MyArr'range loop
Put_Line("Enter Element " & Integer'Image(i));
Get(MyArr(i));
end loop;
end;
end sort;
Thanks in advance :)
Your Problem is that you are insisting on writing Ada code using c - Style programming paradigms.
Firstly:
The declarations:
Type Arr is array(1..20) of Integer;
Type int_access is access Arr;
MyArr : int_access;
Where you use Int_Acc : in out int_access as parameters to procedures are useless in Ada. You are trying to pass a pointer to an array in (which you are doing!), but you should just pass your Type Arr as in out - The Ada compiler knows to do this as a pointer!
Secondly:
I cannot see where you actually allocate any memory to MyArr. This is a possible source of your runtime error. (when you write to or index an array that does not exist, i would expect to have a problem!)
Thirdly:
You seem to be mixing fixed length arrays with variable length input. If N > 20, you will have a problem.
Fourthly:
Insulting the language is not the best way of getting help from those who like it.
NWS has nailed it : there is a pointer, but no array there.
But it's clear that you have learned C, which leaves you with a lot to learn about other languages including Ada. There really are better ways of doing many things, that aren't taught to C programmers because C doesn't allow them.
Allocating variable sized arrays without pointers, malloc and free for example...
Type Arr is array(positive range <>) of Integer; -- of any size
begin
Put_Line("Enter Number Of Elements Of Array");
Get(n);
declare -- now we know the size
My_Arr : Arr(1 .. n);
begin -- My_Arr is in scope until the end of this block
...
end;
end sort;
Using the type system better...
Bad programming :
for i in 1 .. n loop
Get(MyArr(i));
end loop;
HeapSort(MyArr,n);
for i in 1 .. n loop
Put_Line(Integer'Image(MyArr(i)));
end loop;
This is bad because it violates the DRY principle : loop bounds repeated, and something that hopefully represents the array size passed around as a separate parameter... a maintenance nightmare if you decide to rename n to something meaningful for example.
better programming : Use the type system. Recognise that merely declaring an array has declared a new subtype of integer, representing the index of the array. You can access it as My_Arr'range, and the high bound as My_Arr'last.
for i in My_Arr'range loop
Get(MyArr(i));
end loop;
HeapSort(MyArr);
for i in My_Arr'range loop
Put_Line(Integer'Image(MyArr(i)));
end loop;
And accidents such as redefining n after the array declaration can no longer generate buffer overflows.
NOTE: Heapsort now gets its range from the array. (Max_Heapify may still need a separate parameter to operate on subsets of the array)
Arguably best - if it makes the intent clearer - name the index datatype explicitly and use it...
declare -- now we know the size
subtype My_Range is positive range 1 .. n;
My_Arr : Arr(My_Range);
begin -- My_Arr is in scope until the end of this block
for i in My_Range loop ...
And lastly, which do you prefer; a Storage_Error exception immediately the bug occurs (writing to memory you forgot to allocate) or something odd happening much later because something scribbled across another variable?
EDIT
Having cleared up the major issues two more subtle ones remain...
If I compile the modified program (in Gnat 4.8) I get several warnings : one of them is important and tells you exactly what the problem is...
Most of the warnings stem from the fact that
for i in My_Arr'range loop
declares its own loop variable i which hides any existing in-scope declaration. So you can tidy up the code by removing the unnecessary declarations.
What remains is:
sort.adb:51:28: warning: loop range may be null
sort.adb:51:28: warning: bounds may be wrong way round
The for loop bounds are empty ranges, reversed...
1 .. 3 declares a subtype with 3 values
reverse 1 .. 3 declares the same subtype and iterates backwards over it.
But 3 .. 1 declares an EMPTY subtype (containing NO valid values) so iterating over it - either way round - does precisely nothing.
Hopefully that is the missing part of the puzzle. I'm not clear why one faulty loop gets this warning while the other (at line 38) doesn't...
if j<n **and then** Int_Acc(j+1)>Int_Acc(j) then
j:=j+1;
I think you want just 'and' instead of 'and then,' although I haven't looked at Ada code in years.
Did that compile?

Convert Enum to Binary (via Integer or something similar)

I have an Ada enum with 2 values type Polarity is (Normal, Reversed), and I would like to convert them to 0, 1 (or True, False--as Boolean seems to implicitly play nice as binary) respectively, so I can store their values as specific bits in a byte. How can I accomplish this?
An easy way is a lookup table:
Bool_Polarity : constant Array(Polarity) of Boolean
:= (Normal=>False, Reversed => True);
then use it as
B Boolean := Bool_Polarity(P);
Of course there is nothing wrong with using the 'Pos attribute, but the LUT makes the mapping readable and very obvious.
As it is constant, you'd like to hope it optimises away during the constant folding stage, and it seems to: I have used similar tricks compiling for AVR with very acceptable executable sizes (down to 0.6k to independently drive 2 stepper motors)
3.5.5 Operations of Discrete Types include the function S'Pos(Arg : S'Base), which "returns the position number of the value of Arg, as a value of type universal integer." Hence,
Polarity'Pos(Normal) = 0
Polarity'Pos(Reversed) = 1
You can change the numbering using 13.4 Enumeration Representation Clauses.
...and, of course:
Boolean'Val(Polarity'Pos(Normal)) = False
Boolean'Val(Polarity'Pos(Reversed)) = True
I think what you are looking for is a record type with a representation clause:
procedure Main is
type Byte_T is mod 2**8-1;
for Byte_T'Size use 8;
type Filler7_T is mod 2**7-1;
for Filler7_T'Size use 7;
type Polarity_T is (Normal,Reversed);
for Polarity_T use (Normal => 0, Reversed => 1);
for Polarity_T'Size use 1;
type Byte_As_Record_T is record
Filler : Filler7_T;
Polarity : Polarity_T;
end record;
for Byte_As_Record_T use record
Filler at 0 range 0 .. 6;
Polarity at 0 range 7 .. 7;
end record;
for Byte_As_Record_T'Size use 8;
function Convert is new Ada.Unchecked_Conversion
(Source => Byte_As_Record_T,
Target => Byte_T);
function Convert is new Ada.Unchecked_Conversion
(Source => Byte_T,
Target => Byte_As_Record_T);
begin
-- TBC
null;
end Main;
As Byte_As_Record_T & Byte_T are the same size, you can use unchecked conversion to convert between the types safely.
The representation clause for Byte_As_Record_T allows you to specify which bits/bytes to place your polarity_t in. (i chose the 8th bit)
My definition of Byte_T might not be what you want, but as long as it is 8 bits long the principle should still be workable. From Byte_T you can also safely upcast to Integer or Natural or Positive. You can also use the same technique to go directly to/from a 32 bit Integer to/from a 32 bit record type.
Two points here:
1) Enumerations are already stored as binary. Everything is. In particular, your enumeration, as defined above, will be stored as a 0 for Normal and a 1 for Reversed, unless you go out of your way to tell the compiler to use other values.
If you want to get that value out of the enumeration as an Integer rather than an enumeration value, you have two options. The 'pos() attribute will return a 0-based number for that enumeration's position in the enumeration, and Unchecked_Conversion will return the actual value the computer stores for it. (There is no difference in the value, unless an enumeration representation clause was used).
2) Enumerations are nice, but don't reinvent Boolean. If your enumeration can only ever have two values, you don't gain anything useful by making a custom enumeration, and you lose a lot of useful properties that Boolean has. Booleans can be directly selected off of in loops and if checks. Booleans have and, or, xor, etc. defined for them. Booleans can be put into packed arrays, and then those same operators are defined bitwise across the whole array.
A particular pet peeve of mine is when people end up defining themselves a custom boolean with the logic reversed (so its true condition is 0). If you do this, the ghost of Ada Lovelace will come back from the grave and force you to listen to an exhaustive explanation of how to calculate Bernoulli sequences with a Difference Engine. Don't let this happen to you!
So if it would never make sense to have a third enumeration value, you just name objects something appropriate describing the True condition (eg: Reversed_Polarity : Boolean;), and go on your merry way.
It seems all I needed to do was pragma Pack([type name]); (in which 'type name' is the type composed of Polarity) to compress the value down to a single bit.

How to read byte headers of untyped files and then use and display that data when they are file streams in Free Pascal and Lazarus

I am trying to learn Free Pascal using Lazarus and one of my pet projects involves reading the 64 byte headers of a particular set of untyped files that cannot be read and displayed using text or ASCII related procedures (so cannot be outputted directly to Memo boxes etc).
So far, I have devised the following code which does, I think, read in the 64 bytes of the header and I am using TStreams and a "Select Directory" dialog box to do this, based on advice received via the Lazarus IRC. My question though is how to actually USE the data that is read into the buffer from the header? For example, in the headers, there are sequences of 8 bytes, then 16 bytes, then 2 bytes and so on that I want to "work on" to generate other output that will eventually be converted to a string to go into my string grid.
Some of what I have so far is based on what I found here written by Mason Wheeler near the end (http://stackoverflow.com/questions/455790/fast-read-write-from-file-in-delphi) but it only shows how to read it in, not how to use it. I also read this (http://stackoverflow.com/questions/4309739/best-way-to-read-parse-a-untyped-binary-file-in-delphi) but again, it shows you how to READ the data too, but not subsequently USE the data. Any guidance wamrly received! So far, the code below just outputs single value integer numbers to the edit box, as opposed to, say, a range of 8 hexadecimal values.
PS - I am new to programming so please be gentle! Nothing too complex.
procedure TForm1.ProbeFile(FileIterator: TFileIterator);
type
TMyHeader = Array[1..64] of packed record
First8Bytes,
Next16Bytes,
Next2Bytes: byte;
end;
var
FI : TFileIterator; //File Iterator class
SG : TStringGrid;
NumRead : SmallInt;
FileToProbe: TStream;
header: TMyHeader;
begin
FI := TFileIterator.Create;
SG := TStringGrid.Create(self);
// Open the file and read the header
FileToProbe := TFileStream.Create(FileIterator.FileName, fmOpenRead);
try
FileToProbe.seek(0, soFromBeginning);
FileToProbe.ReadBuffer(header, SizeOf(header));
edit1.text := IntToStr(header[0].First8Bytes); // Just outputs '0' to the field? If I try '10' it ooutputs '29' and so on
finally
FileToProbe.Free;
end;
Please forgive me if I misunderstood your question.
As I understand it there is a header of 64 bytes. The first 8 bytes belong together, then the next 16 bytes and finally another 2 bytes.
To me it seems the declaration for this header should be:
TMyHeader = packed record
First8Bytes: array[0..7] of byte;
Next16Bytes: array [0..15] of byte;
Next2Bytes: array [0..1] of byte;
// add more if you like
end;
This recordtype has a size of 8+16+2 = 26 bytes.
Your code that reads the header looks ok to me, So I won't repeat that.
The next16bytes in your header can be retrieved, for example, like this:
edit1.text:= '';
// needs a declaration of a variable "i" as integer
for i:= 0 to 15 do
edit1.text:= edit1.text + IntToStr(header.next16bytes[i]) + '-';
Change the value of the first byte in the next2bytes part of your header as follows (again as an example):
header.next2bytes[0]:= 123;
Finally, you could write your changes back to the header of the file with help of the filetoprobe.writebuffer method.

Resources