Memory alignment and new
Does c++ guarantee a 4-byte aligned block of memory with new?
it seems like "uint32_t *ptr = new uint32_t[someNumber]; " ought to be guaranteed to be aligned for platforms that require word alignment.
C++ guarantees that the memory pointed to will be correctly aligned for *any* complete object type whose size is no greater than the requested size. for a uint32_t, on most implementations, this is a 4-byte aligned block. and, even if an array of char (of size >= sizeof uint32_t) is allocated, the block will be correctly aligned so that it is safe to place a uint32_t in it.
IS 18.104.22.168 / 2: The allocation function attempts to allocate the requested amount of storage. If it is successful, it shall return the address of the start of a block of storage whose length in bytes shall be at least as large as the requested size.
The pointer returned shall be suitably aligned so that it can be converted to a pointer of any complete object type and then used to access the object or array in the storage allocated
IS 5.3.4 / 10: A new-expression passes the amount of space requested to the allocation function as the first argument of type std::size_t. That argument shall be no less than the size of the object being created; it may be greater than the size of the object being created only if the object is an array. For arrays of char and unsigned char, the difference between the result of the new-expression and the address returned by the allocation function shall be an integral multiple of the most stringent alignment requirement of any object type whose size is no greater than the size of the array being created. [Note: Because allocation functions are assumed to return pointers to storage that is appropriately aligned for objects of any type, this constraint on array allocation overhead permits the common idiom of allocating character arrays into which objects of other types will later be placed. ]
Last edited by vijayan; 02-07-2009 at 12:56 PM.
The same is true for malloc btw.
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center