[fpc-devel] Wrong docs: not initialized global variables

Ralf Quint freedos.la at gmail.com
Tue Jul 3 19:00:09 CEST 2018


On 7/3/2018 9:40 AM, Ondrej Pokorny wrote:
>
> 1.) SetLength itself produces an unitialized block of data within the
> variable if the new length is bigger than the old length.
>
> Therefore it would be more appropriate to get an "uninitialized
> warning" after SetLength:
>
> program Project1;
> var
>   S: string;
> begin
>   SetLength(S, 10); // <<< warning here     --->> WHY ????
>   Writeln(S[2]);    // <<< no warning here  --->> WHY ????
> end. 
The program does EXACTLY what you told it to do and the compiler gives
you an explicit warning that that what you are doing is potentially
wrong/dangerous.
If you set the length of a string, without it having been
initialized/assigned a value, all you do is to tell the program that you
have now a string of a specified length. And as long as you do not
exceed that specified length, there is no reason for the compiler to
complain about it. YOU explicitly defined that accessing any
character/element up to that defined length is valid!
You as a programmer failed to heed the warning at the SetLength()
function and adjusted your code accordingly.  You as a programmer should
realize that there are random characters in the string if you extend the
length of the string. How is the extended length to be initialized?
Blanks (0x20), Zeroes (0x00)? What about the following example?

Program ABC;
Var S : String;
begin
  S := '12345';
  SetLength (S, 10);
  WriteLn (S [2]);
  WriteLn (S [7]);
end.   

Ralf



More information about the fpc-devel mailing list