Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2012-03

Pointer to temporary string

3 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

cobines

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

Reply by email

Jonas Maebe
to cobines
cobines wrote
Is storing and using pointers to temporary strings safe?

No.

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?

The only thing you can prove is finding code that crashes. You can't prove that it's safe, because it's impossible to prove a negative (namely that no code sequence exists that will crash).

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.

Nevertheless it's not safe. It depends on management of temporary variables of the compiler, which in itself depends on the performed optimizations and compiler version. Just don't do it.

Jonas

Reply by email