Memory alignment and new


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 4 of 4

Thread: Memory alignment and new

  1. #1
    Join Date
    Oct 2007
    Posts
    369

    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.

  2. #2
    Join Date
    Dec 2007
    Posts
    401
    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 3.7.3.1 / 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.
    ...[elided]...
    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
    ...[elided]...

    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 11:56 AM.

  3. #3
    Join Date
    Oct 2007
    Posts
    369
    Thanks a bunch!

  4. #4
    Join Date
    Nov 2003
    Posts
    4,118
    The same is true for malloc btw.
    Danny Kalev

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center