[issue18835] Add aligned memory variants to the suite of PyMem functions/macros

Nathaniel Smith report at bugs.python.org
Wed Oct 25 17:38:08 EDT 2017


Nathaniel Smith <njs at pobox.com> added the comment:

> I'm not sure that it's a good idea to provide a "aligned malloc" fallback if such fallback would be inefficient. For example, we would have to overallocate the memory block not only for the requested alignement, but also allocates extra sizeof(size_t) bytes, *in each* aligned memmory block, to store the size of the alignment itself, to recover the original pointer... to finally be able to call free().

You can re-use the same bytes for padding and to store the offset. The main tricky thing is that for an alignment of N bytes you need to overallocate N bytes instead of (N-1). (In the worst case, malloc returns you a pointer that's already N-byte aligned, and then you have to advance it by a full N bytes so that you have some space before the pointer to store the offset.)

Also you want to do a little N = max(N, sizeof(whatever int type you use)) at the beginning to make sure it's always big enough, but this is trivial (and really even a uint16_t is plenty big to store all reasonable alignments). And make sure that N is a power-of-two, which guarantees that whatever value malloc returns will be shifted by at least malloc's regular alignment, which is guaranteed to be large enough to store a standard int type (on reasonable systems).

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue18835>
_______________________________________


More information about the Python-bugs-list mailing list