www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - core.stdc.stdlib.malloc & alignment

reply captaindet <2krnk gmx.net> writes:
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
Jun 28 2016
parent reply Hiemlick Hiemlicker <HH reign.com> writes:
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.
Jun 28 2016
parent captaindet <2krnk gmx.net> writes:
On 2016-06-29 14:39, Hiemlick Hiemlicker wrote:
 Yes, the C standard requires malloc to be aligned to the platform size(4
 for 32bit, 8 for 64-bit).
just what i was hopping for. thanks!
Jun 28 2016