1

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?

Tom Brunberg
  • 20,312
  • 8
  • 37
  • 54
Thomas
  • 677
  • 1
  • 5
  • 19
  • `Result` is not initialized before the loop, hence the length overflow. `Randomize` should only be initialized once at program start. – LU RD Jun 27 '16 at 20:22
  • @LURD so Result gets intialized with a random value that is longer than strlength and therefore will never meet the criteria? – Thomas Jun 27 '16 at 20:25
  • See [What is the default value of 'Result' in Delphi?](http://stackoverflow.com/questions/5336863/what-is-the-default-value-of-result-in-delphi). – LU RD Jun 27 '16 at 20:26
  • thanks @LURD. I think i should write the admin as i spent some hours trying to figure out my program freezes. thanks again – Thomas Jun 27 '16 at 20:27
  • Please also note that ordinals 48..57 stands for ASCII characters '0'..'9', (not '0'..'1') and that the result of the function never contains a 'z' (ordinal 122) because `function Random(const ARange: integer): integer` returns a number X which is `0 <= X < ARange` – Tom Brunberg Jun 28 '16 at 07:05
  • It's also possible to have a problem if the function is called with `strlength <= 0`. – Disillusioned Jun 28 '16 at 08:15

1 Answers1

4

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.

Community
  • 1
  • 1
LU RD
  • 34,438
  • 5
  • 88
  • 296