Hairy Pixels via fpc-pascal <fpc-pascal@lists.freepascal.org> schrieb am
Mo., 18. März 2024, 13:30:

>
>
> > On Mar 18, 2024, at 5:29 PM, Michael Van Canneyt via fpc-pascal <
> fpc-pascal@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';
>


Your description is inaccurate: s2 does not point to s1. Instead both point
to the string data with a reference count of 2. If you now change one of
the two (e.g. with SetLength) then a copy of the string data will be
created and that copy will be manipulated.
The memory of the string data will only be reallocated if only one
reference to that data exists.

Regards,
Sven

>
_______________________________________________
fpc-pascal maillist  -  fpc-pascal@lists.freepascal.org
https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal

Reply via email to