[fpc-devel] Strange Problem!
Martin
lazarus at mfriebe.de
Wed Apr 25 22:48:59 CEST 2012
On 25/04/2012 21:11, Amir wrote:
>
> I am not sure what you mean be "your program is not valid". I am
> initializing Result. Modify its content and ...
>
> I already observed that if I use either shortstring or use indices to
> modify Result, this problem does not occur. But still I can't see what
> causes this problem. And I believe it is a bug, isn't it?
>
Try the program at the end.
it will print "x" !!!
Strings a pointers. And they do "copy on write"
s2 := s1;
means that s1 and s2 point to the same memory (not only the same
content, but the same location in mem)
Internally the strig knows, that the memory is used by 2 strings
s2[1] := 'a';
will trigger "copy on write". So s2 gets copied first then modified
using pchar does not trigger such copies.
so the cod modifies the constant you use for initialization.
try
UniqueString(Result);
program Project1;
function Foo: AnsiString;
begin
Result:= ' ';
end;
var
s: String;
p: PChar;
begin
s := Foo;
p := @s[1];
p^ := 'x';
writeln(Foo);
readln;
end.
More information about the fpc-devel
mailing list