Reputation: 707
I am learning delphi on the german site delphi-treff.
they provide a function to generate random string.
https://www.delphi-treff.de/tipps-tricks/object-pascal/strings/zufallstring-generieren/
function RandomString(strlength: integer): string;
var
temp : integer;
begin
randomize;
repeat
temp := random(122); //ggf. erhöhen
if temp in [48..57{0-1}, 65..90{A-Z}, 97..122{a-z}] then
//Kann um beliebige ASCII-Zeichen erweitert werden,
//ggf. den Wert in Random hochsetzen
result := result + Chr(temp);
until length(result) = strlength;
end;
as you can see here:
if temp in [48..57{0-1}, 65..90{A-Z}, 97..122{a-z}] then
they only put 0-1, A-Z and a-z as characters.
However I thought my program crashes because of this function.
so I changed: until length(result) = strlength;
to: until length(result) >= strlength;
and indeed it sometimes is > strlength.
Can someone explain why it is bigger?
It shouldn't be bigger because it only adds 1 character at a time?
Upvotes: 1
Views: 178
Reputation: 34899
Result
is treated as an implicit var
parameter and must be initialized before use. See What is the default value of 'Result' in Delphi?.
In this case an uninitialized Result
parameter will cause the length overflow.
Another issue, Randomize
should only be called once at program start.
Upvotes: 4