[fpc-pascal] Pointer to temporary string

cobines cobines at gmail.com
Sun Mar 11 15:46:30 CET 2012


Hello.

Is storing and using pointers to temporary strings safe? Like in the
following program. I think I remember reading on the mailing list that
it is not, but I cannot find it. How can I prove one way or the other?
I could not get the program to crash, even if I used 20 variables, it
didn't show any wrong result. Valgrind and Dr. Memory didn't show any
problems.

program project1;
{$mode objfpc}{$H+}

function GetNew: String;
var
  i: Integer;
begin
  Result := '';
  for i := 0 to 10 do
    Result := Result + string(chr(Random(Ord('z')-Ord('a'))+Ord('a')));
end;

var
  p1,p2,p3: PChar;
begin
  Randomize;
  p1 := PChar(GetNew);
  p2 := PChar(GetNew);
  p3 := PChar(GetNew);
  WriteLn(string(p1));
  WriteLn(string(p2));
  WriteLn(string(p3));
end.

--
cobines



More information about the fpc-pascal mailing list