Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it acceptable to read outside the bound of an array (string)?

Tags:

delphi

I study a little the Delphi source code, and this look a little ugly for me (in system.pas, procedure ValLong) :

while True do
begin
  case S[I] of
    '0'..'9': Dig := Ord(S[I]) - Ord('0');
  else
    Break;
  end;
  if (Result < 0) or (Result > (High(Integer) div 10)) then
    Break;
  Result := Result*10 + Dig;
  Inc(I);
  Empty := False;
end;

As you can see the only way to get out of the loop is to read outside the boundary of S (a string). Do I miss something and this is an correct practice ?

like image 707
zeus Avatar asked Mar 01 '23 16:03

zeus


1 Answers

Unicode strings, AnsiString and WideString types are always ending with a null character.

From Internal Data Formats-Long String Types:

The NULL character at the end of a string memory block is automatically maintained by the compiler and the built-in string handling routines. This makes it possible to typecast a string directly to a null-terminated string.

So, it is safe to rely on the fact that these types are null terminated. The code example in the question is ok.

Note: I'm assuming range checking is off, since this code is from the RTL. Otherwise, it would have caused an exception when indexing the null character.

like image 129
LU RD Avatar answered Apr 01 '23 12:04

LU RD