[fpc-pascal] AnsiString address changed

Michael Van Canneyt michael at freepascal.org
Mon Mar 18 07:52:21 CET 2024



On Mon, 18 Mar 2024, Hairy Pixels via fpc-pascal wrote:

> Curious, why did the address of "s" change here? Shouldn't the AnsiString be incrementing a reference  count and not actually changing the actual pointer or copying?
>
> Correct me if I'm wrong, AnsiString is ref counted when passing in/out functions but copies on assignment so technically no two AnsiStrings can be shared in two locations, which makes sense because if they were resized they would invalidate each others memory anyways when ReAllocMem is called.
>
> I guess if that's true then there must be only pointer to any AnsiString in any given scope otherwise they could resize and corrupt their memory.
>
> Not sure if that makes sense, I'm struggling to understand myself. :)
>
> ============================================
>
>  procedure PassString(s: AnsiString);
>  begin
>    writeln(hexstr(@s));
>  end;
>
> var
>  s1: AnsiString;
> begin
>  s1 := '123';
>  writeln(hexstr(@s1));
>  PassString(s1);
>  writeln(hexstr(@s1));
> end.
>
> Output:
>
> 000000010259AC00
> 000000016DBC2F80
> 000000010259AC00

An ansistring is a pointer to a memory block.

You are printing the address of S1 and the address of S, i.e. the address of
the pointer itself, not the address of what S (or s1) points to. 
Obviously the address of the s is different of s1.

What you want to do is print hexstr(pointer(s))
if you do that, you'll have the same output 3 times.

Michael.


More information about the fpc-pascal mailing list