Board index » delphi » Strings & EOutOfMemory

Strings & EOutOfMemory

Hi,

I have an application that converts between number types ( Binary, Octal,
Decimal & Hex). However, whenever I try and call this function more than
twice within another, it raises an EOutOfMemory exception and I can't
determine why.

Thanks,

Murdoc

// --------------------------------------

{ Converts a decimal number to a binary string of a specified length }
function convertDecimaltoBinary(Number, Bits: Integer) : String;
var
   BinString : String;
   I, MaxDigits : Integer;
begin
     if Number = 0 then
     begin
        SetLength(BinString,Bits);
        for I := 1 to Length(BinString) do
            BinString[I] := '0';
     end
     else
         MaxDigits := Floor(Log2(Number)) + 1;
         if Bits < MaxDigits then
            Bits := MaxDigits;
         SetLength(BinString,Bits);
         for I := 1 to Bits do
             if Number > Power(2,I) then
             begin
                BinString[Bits-I] := '1';
                Number := Number - Floor(Power(2,I));
             end
             else
                 BinString[Bits-I] := '0';
     Result := BinString;
end;

 

Re:Strings & EOutOfMemory


Quote
"Murdoc" <murdo...@hotmail.com> wrote in message news:ah7ti4
>          for I := 1 to Bits do
>              if Number > Power(2,I) then
>              begin
>                 BinString[Bits-I] := '1';
>                 Number := Number - Floor(Power(2,I));
>              end
>              else
>                  BinString[Bits-I] := '0';

The index calculation into BinString is returning a value out of the range
of the string. I suspect that you are running without range checking
enabled. Among other things, the code is clobbering memory.

function IntToBin (num, bits : integer) : string;

var lth, i, lastSet, argSize : integer;

begin
argSize := SizeOf (num) * 8;
lth := Max (argSize, bits);
result := StringOfChar ('0', lth);
lastSet := lth;
for i := lth downto Max (1, lth - argSize) do
     begin
     if (num and $01) > 0
     then begin
          result [i] := '1';
          lastSet := i;
          end;
     num := num shr 1;
     end;
if (lth - lastSet) >= bits
then Delete (result, 1, lastSet - 1)
else Delete (result, 1, lth - bits);
end;

Other Threads