[fpc-devel] Aligned dynamic arrays

Ryan Joseph ryan at thealchemistguild.com
Thu Mar 28 02:31:22 CET 2019

> On Mar 27, 2019, at 9:13 PM, Martin Frb <lazarus at mfriebe.de> wrote:
> 2 Ideas, well 1 Idea, 1comment...
> The Idea:
> Would it not be easier to:
> - allocate mem, with extra space for align, unless memmanager can handle align.
> - return the alligned pointer for the array, so all array ops will work exactly as they currently do
> - prefix/extend the array header by a field "OffsetToMemAlloc" (that is the reverse, of what I understand your padding would do, but still can be a positive number, the code knows to subtract it where needed)
> This field would allow to correctly get the memory for re-alloc/free operations.

I think we’re basically talking about the same thing but it’s hard to know without seeing code. The biggest challenge is that in order to get the array header you need to subtract from the “head" (the start of the elements). Right now it’s easy because you just subtract the size of the header but if the head is now aligned and 100’s of bytes away from the start of the header then you need to subtract that amount also. In fact technically speaking the offset field is adjacent to the start of elements and could be many bytes away from the actual header.

Here’s the basic structure:


[head] being the start of the elements (the pointer to the first element of the array) and aligned to the requested amount. Keep in mind the head is the pointer which is passed around so we need to subtract back from that in order to access the header, which contains the array high value and the refcount.

Look at the dynarr.inc in the /rtl directory to see what I’m talking about. Pretty hard to explain without seeing how Sven did things. :)

> The comment:
> As for extending the array header, maybe introduce a new data type "aligned array".
> So normal arrays do not have that field in there header.

The plan was to make a “SetLengthAligned” or add an extra parameter to “SetLength”, i.e, SetLength(arr,100,true). I have no preference, what ever the compiler team wants.

	Ryan Joseph

More information about the fpc-devel mailing list