[fpc-pascal] AnsiString address changed

Tomas Hajny XHajT03 at hajny.biz
Mon Mar 18 13:51:09 CET 2024


On 2024-03-18 13:29, Hairy Pixels via fpc-pascal wrote:
>> On Mar 18, 2024, at 5:29 PM, Michael Van Canneyt via fpc-pascal 
>> <fpc-pascal at lists.freepascal.org> wrote:
>> 
>> Of course there must be, that's the whole point of copy-on-write.
>> 
>> As soon as one reference is changed, a copy is made if the reference 
>> count
>> is larget than 1, and this copy is changed.
> 
> Oh, it does copy on write. I see now that by looking at the pointer 
> addresses.
> 
> So what happens if you do this? s2 is pointing to s1 but then you
> change the size of s1 and ReAllocMem gets called and invalidates the
> pointer to the original s1. How does s2 know this and not access
> corrupted memory now?
> 
>   s1 := '123';
>   s2 := s1;
>   s1 := 'xxxxxxxxxxxx';

 From user point of view, the result is the same as when s1 and s2 are 
declared as shortstring (i.e. s2 = '123' and s1 = 'xxxxxxxxxxxxx'). From 
technical point of view, the original location is used for s2 (with 
reference count 1), whereas s1 points to a new location (with reference 
count also 1 at that point in time).

Tomas


More information about the fpc-pascal mailing list