core.stdc.stdlib.malloc & alignment
Hiemlick Hiemlicker via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jun 28 19:39:17 PDT 2016
On Wednesday, 29 June 2016 at 02:24:55 UTC, captaindet wrote:
> is there an alignment guarantee for core.stdc.stdlib.malloc?
>
> more specifically, using DMD and compiling for 32bit on
> windows, can i assume proper alignment for int or uint
> variables?
>
> background: i like to re-use a (ubyte) buffer, sometimes it
> will store only bytes, sometimes it shall store uints.
>
> thanks
Yes, the C standard requires malloc to be aligned to the platform
size(4 for 32bit, 8 for 64-bit).
Alternatively, you can use code like
size_t capacity = capacity;
size_t size = T.sizeof*capacity;
enforce(size > 0, "Cannot allocate fixed array of size 0.");
if (mem is null)
mem = cast(T*)malloc(size+Alignment);
else
mem = cast(T*)realloc(mem, size+Alignment);
enforce(cast(int)mem > 0, "Could not malloc memory block.");
// Adjust memory pointer to be aligned
size_t tmp = (cast(size_t)mem) & (Alignment - 1);
size_t ofs = (Alignment - tmp) & (Alignment - 1);
mem = cast(T*)((cast(size_t)mem) + ofs);
// Add extra space to be additional end capacity.
capacity = cast(size_t)((size + Alignment - ofs)/T.sizeof);
which malloc's a block of memory and aligns it.
More information about the Digitalmars-d-learn
mailing list