[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: protection against buffer overflows



Alvin Oga <aoga@Maggie.Linux-Consulting.com> wrote on 24/01/2002 (11:13) :
> 
> hi ya ralf
> 
> i would have thought that gcc would barf on b[20]='X'
> and similarly for theother variable assignments since its not prev
> allocated/defined.. and yet explicitly assigned (incorrectly??)...

Why there are no range tests in C.

Lets do it Ada 95 instead:

I have tired to make the code as similar to C as possible so it is a bit
ackward Ada-wise but here goes:

Note I have written here the line numbers in front of the code so that
it is easier to check with the compiler results.

file: example.adb

------------------------------------------------------------------------
 1 with Ada.Text_IO;   use Ada.Text_IO;  -- equvalent to #include <stdio.h>
 2
 3 procedure example is
 4    --  Ada has it's own String type, but lets do what the C example does.
 5    type C_String_Type is array (1..10) of Character;
 6
 7    a : C_String_type;
 8    b : C_String_type;
 9 begin
10
11    a := ('1','2','3','4','5','6','7','8','9', others => ' ');
12    --  others => ' '  just means that the rest of the array will be
13    --  filled with spaces.
14
15    --  Printing a becomes ackward as I didn't use the Ada Strings type
16    --  in this example, but as you can see the for loop is nice.
17
18    Put ("a: ");
19    for i in C_String_Type'Range loop
20       Put (a(i));
21    end loop;
22
23    New_Line;
24
25    --  Now the faulty code.
26    b (20) := 'X';
27    b (21) := 'Y';
28    b (22) := 'Z';
29
30    --  No point in printing again as the code will never reach here.
31 end example;
------------------------------------------------------------------------

Now when compiling we get:

   % gnatmake example.adb 

   gnatgcc -c example.adb
   example.adb:26:07: warning: value not in range of subtype of "Standard.integer" defined at line 5
   example.adb:26:07: warning: "constraint_error" will be raised at run time
   example.adb:27:07: warning: value not in range of subtype of "Standard.integer" defined at line 5
   example.adb:27:07: warning: "constraint_error" will be raised at run time
   example.adb:28:07: warning: value not in range of subtype of "Standard.integer" defined at line 5
   example.adb:28:07: warning: "constraint_error" will be raised at run time
   gnatbind -x example.ali
   gnatlink example.ali

And if one ignore the wranings and run the program:

   % ./example

   a: 123456789 

   raised CONSTRAINT_ERROR : example.adb:26

So as the compiler said the code would not run without a constraint
error being raised at line 26 which is the faulty code.

Preben Randhol
-- 
                 «For me, Ada95 puts back the joy in programming.»



Reply to: