title: best cross-platform method to get aligned memory
body: <p>Here is the code I normally use to get aligned memory with Visual Studio and GCC</p>
  
  <pre><code>inline void* aligned_malloc(size_t size, size_t align) {
      void *result;
      #ifdef _MSC_VER 
      result = _aligned_malloc(size, align);
      #else 
       if(posix_memalign(&amp;result, align, size)) result = 0;
      #endif
      return result;
  }
  
  inline void aligned_free(void *ptr) {
      #ifdef _MSC_VER 
          _aligned_free(ptr);
      #else 
        free(ptr);
      #endif
  
  }
  </code></pre>
  
  <p>Is this code fine in general?  I have also seen people use <code>_mm_malloc</code>, <code>_mm_free</code>.  In most cases that I want aligned memory it's to use SSE/AVX.  Can I use those functions in general?  It would make my code a lot simpler.</p>
  
  <p>Lastly, it's easy to create my own function to align memory (see below).  Why then are there so many different common functions to get aligned memory (many of which only work on one platform)?</p>
  
  <p>This code does 16 byte alignment.</p>
  
  <pre><code>float* array = (float*)malloc(SIZE*sizeof(float)+15);
  
  // find the aligned position
  // and use this pointer to read or write data into array
  float* alignedArray = (float*)(((unsigned long)array + 15) &amp; (~0x0F));
  
  // dellocate memory original "array", NOT alignedArray
  free(array);
  array = alignedArray = 0;
  </code></pre>
  
  <p>See: <a href="http://www.songho.ca/misc/alignment/dataalign.html" rel="noreferrer">http://www.songho.ca/misc/alignment/dataalign.html</a> and
  <a href="https://stackoverflow.com/questions/227897/solve-the-memory-alignment-in-c-interview-question-that-stumped-me">How to allocate aligned memory only using the standard library?</a></p>
  
  <p>Edit:
  In case anyone cares, I got the idea for my aligned_malloc() function from Eigen (Eigen/src/Core/util/Memory.h)</p>
  
  <p>Edit:
  I just discovered that <code>posix_memalign</code> is undefined for MinGW.  However, <code>_mm_malloc</code> works for Visual Studio 2012, GCC, MinGW, and the Intel C++ compiler so it seems to be the most convenient solution in general.  It also requires using its own <code>_mm_free</code> function, although on some implementations you can pass pointers from <code>_mm_malloc</code> to the standard <code>free</code> / <code>delete</code>.</p>