How to align pointer

stack alignment
c align macro
aligned memory allocation
64 bit aligned address
aligned vs unaligned memory access
natural alignment
word alignment in computer architecture
abi alignment

How do I align a pointer to a 16 byte boundary?

I found this code, not sure if its correct

char* p= malloc(1024);

if ((((unsigned long) p) % 16) != 0) 
{
     unsigned char *chpoint = (unsigned char *)p;        
     chpoint += 16 - (((unsigned long) p) % 16);
     p = (char *)chpoint;
}

Would this work?

thanks

C++0x proposes std::align, which does just that.

// get some memory
T* const p = ...;
std::size_t const size = ...;

void* start = p;
std::size_t space = size;
void* aligned = std::align(16, 1024, p, space);
if(aligned == nullptr) {
    // failed to align
} else {
    // here, p is aligned to 16 and points to at least 1024 bytes of memory
    // also p == aligned
    // size - space is the amount of bytes used for alignment
}

which seems very low-level. I think

// also available in Boost flavour
using storage = std::aligned_storage_t<1024, 16>;
auto p = new storage;

also works. You can easily run afoul of aliasing rules though if you're not careful. If you had a precise scenario in mind (fit N objects of type T at a 16 byte boundary?) I think I could recommend something nicer.

How to align pointer, C++0x proposes std::align , which does just that. // get some memory T* const p = ; std::size_t const size = ; void* start = p; std::size_t space = size; void*  Hands down the fastest way to align a pointer is to use 2's complement math. You need to invert the bits, add one, and mask off the 2 (for 32-bit) or 3 (for 64-bit) least significant bits. The result is an offset that you then add to the pointer value to align it. Works great for 32 and 64-bit numbers.

Try this:

It returns aligned memory and frees the memory, with virtually no extra memory management overhead.

#include <malloc.h>
#include <assert.h>

size_t roundUp(size_t a, size_t b) { return (1 + (a - 1) / b) * b; }

// we assume here that size_t and void* can be converted to each other
void *malloc_aligned(size_t size, size_t align = sizeof(void*))
{
    assert(align % sizeof(size_t) == 0);
    assert(sizeof(void*) == sizeof(size_t)); // not sure if needed, but whatever

    void *p = malloc(size + 2 * align);  // allocate with enough room to store the size
    if (p != NULL)
    {
        size_t base = (size_t)p;
        p = (char*)roundUp(base, align) + align;  // align & make room for storing the size
        ((size_t*)p)[-1] = (size_t)p - base;      // store the size before the block
    }
    return p;
}

void free_aligned(void *p) { free(p != NULL ? (char*)p - ((size_t*)p)[-1] : p); }
Warning:

I'm pretty sure I'm stepping on parts of the C standard here, but who cares. :P

Generating Aligned Memory, Given a pointer ptr to a buffer of size space, returns a pointer aligned by the specified alignment for size number of bytes and decreases space  Given a pointer ptr to a buffer of size space, returns a pointer aligned by the specified alignment for size number of bytes and decreases space argument by the number of bytes used for alignment. The first aligned address is returned.

In glibc library malloc, realloc always returns 8 bytes aligned. If you want to allocate memory with some alignment which is a higher power 2 then you can use memalign and posix_memalign. Read http://www.gnu.org/s/hello/manual/libc/Aligned-Memory-Blocks.html

std::align, If the type-checking system is overridden by an explicit cast or the pointer is converted to a void pointer ( void * ) and then to a different type, the alignment of an  #ifndef align_up #define align_up(num, align) \ (((num) + ((align) - 1)) & ~((align) - 1)) #endif. Note that this operates on powers of two, so we will have to limit our alignment values to powers of two. aligned_malloc. Let’s start with aligned_malloc. Recall the prototype: void * aligned_malloc(size_t align, size_t size)

posix_memalign is one way: http://pubs.opengroup.org/onlinepubs/009695399/functions/posix_memalign.html as long as your size is a power of two.

The problem with the solution you provide is that you run the risk of writing off the end of your allocated memory. An alternative solution is to alloc the size you want + 16 and to use a similar trick to the one you're doing to get a pointer that is aligned, but still falls within your allocated region. That said, I'd use posix_memalign as a first solution.

Data structure alignment, For example, a processor might require that a 4-byte integer or pointer referenced as a single object be word aligned–at an address that's a  Dish Pointing Basics. To receive DIRECTV broadcast signals, your standard satellite dish must be correctly positioned, which is fairly simple to do yourself using DIRECTV's Dish Pointer below. If you've purchased a DIRECTV multi-satellite system, we highly recommend professional installation.

EXP36-C. Do not cast pointers into more strictly aligned pointer types, If space is not enough to accommodate for the requested aligned buffer, the function returns a null pointer, and alters neither ptr nor space. Parameters. alignment  Services we offer. Apart from offering our DishPointer service on this website and our award-winning apps for IOS / Apple devices and Android smartphones and tablets to align your satellite dish, we are providing business solutions to satellite professionals all around the world for over a decade now.

Computing properly aligned pointer values, This post shows that modern optimizing C compilers assume that the source code they are compiling respects memory alignment constraints,  Before you can align it, you have to make sure that you meet the following conditions: 1. Your finderscope has adjustable knobs. Some telescopes are fixed and therefore do not need to be adjusted. 2.

align - C++ Reference, CPUs used to perform better when memory accesses are aligned, that is when the pointer value is a multiple of the alignment value. The alignment when memory is allocated on the heap depends on which allocation function is called. For example, if you use malloc, the result depends on the operand size. If arg >= 8, the memory returned is 8 byte aligned. If arg < 8, the alignment of the memory returned is the first power of 2 less than arg.

GCC always assumes aligned pointer accesses – TrustInsoft,

Comments
  • What toolchain and platform? Alignment is a property of the implementation. Also, why do you want to do this? Do you really mean C++? Because your code is valid C but not valid C++.
  • stackoverflow.com/questions/4840410/how-to-align-a-pointer-in-c may be of interest (since you appear to be writing C anyway).
  • Do not use that code. If you try to free p it's going to cause you all kinds of problems. Furthermore, you no longer have a guarantee about how much memory you actually have (somewhere between 1009 and 1024)
  • I had a piece of code that allowed you to do something like this (provided that you used a custom free function), but which did not require outside memory -- it simply allocated a bit more than you requested, and freed that at the end. I'll post it here soon, if I find it.
  • I re-wrote it and posted it; try using it and see if it's helpful.
  • This is an old answer, nevertheless there are two points: 1. typedef std::aligned_storage<1024, 16> storage; is wrong. storage should be typedefed to either aligned_storage_t<1024,16> or aligned_storage<1024,16>::type if this approach is to be used. 2. There is no guarantee for that to work with overaligned types. It may be the case that alignof(aligned_storage_t<1024,N>) < N if N > alignof(std::max_align_t).
  • @Pixelchemist Thanks, fixed. As for over-aligned types, that’s less to do with std::aligned_storage_t itself and more with their implementation-defined nature. What to do exactly is best left to the programmer.
  • This is a couple of years late, but there's a cool intptr_t stashed away in cstdint that is guaranteed to be convertible to and from pointers and is guaranteed to support arithmetic.
  • @mehrdad can you put some comments in you code. Also why you used (2*align) "void *p = malloc(size + 2 * align);" in malloc and let's if I want alignment of 8/16 that the above code will work fine ?
  • @eswaat: roundUp(base, align) + align can easily increment base up by more than just align.
  • @Mehrdad Sorry didn't get you, can you please elaborate or put some comments in your code like why 2*align etc etc ? Asking more but this is first time so. Thanks.
  • @eswaat: Does this help?
  • size_t isn't guaranteed to have the same size as a pointer. (I've used 16 bits size_t with 32 bits pointers in DOS time), unsigned long is in fact often a better choice that size_t for that (but isn't formally guaranteed either and won't work on windows 64 bit). uintptr_t has been introduced in C99 and C++0X for that purpose and is often available as extension before. C++0X even offer a standard way to align (see Luc's answer)
  • well, x86 real mode can't be discussed in the same sentence with C++ 0x, can it? Regarding the real mode long pointers, the pointer arithmetic was rather non-trivial back then, so it had to be re-written anyway. On top of that, the size of the pointers returned by the allocation functions used to depend on the version of the CRT library used. Some programming environments adjusted size_t definition accordingly.