[fpc-pascal] Dynamic arrays, yet another pitfall

Jürgen Hestermann juergen.hestermann at gmx.de
Mon Feb 17 18:28:15 CET 2014


Am 2014-02-17 18:01, schrieb Martin Frb:
 > On 17/02/2014 16:40, Jürgen Hestermann wrote:
 > It appears, that the copy-on-setlength is intended. So in that the documentation is right.

It is intended but is was not mentioned in the documentation.
Therefore this whole thread exists at all.


 > As for this being a good or bad idea, is a different question. (There are pro and con apparently). But even if we concluded it bad, changing it now would be by far worse.
 > Besides I believe it is not possible
 > setlength(a,10)
 > b := a;
 > setlength(a,1200)
 > The data pointed to by both a and b (before the final setlength) has a refcount of 2. But it has no info where a and b are. So in SetLength(a, 1200) it is unknown where  the other reference (b) is. And that means b can not follow this change.

You can only say this because you know how dynamic arrays are implemented. But someone who only has to rely on the documentation does not know where both pointers point to (he not even knows they are pointers). So what should he assume? There could be an intermediate data structure that holds the pointer to the data array in the same way as it holds the reference counter. So 2 pointers pointing to the same data structure and only this structure is changed by SetLength. Then there would be no copy on write with SetLength. But how can we know?






More information about the fpc-pascal mailing list