Quantcast
Viewing latest article 5
Browse Latest Browse All 18

Answer by Chris for How to allocate aligned memory only using the standard library?

MacOS X specific:

  1. All pointers allocated with malloc are 16 bytes aligned.
  2. C11 is supported, so you can just call aligned_malloc (16, size).

  3. MacOS X picks code that is optimised for individual processors at boot time for memset, memcpy and memmove and that code uses tricks that you've never heard of to make it fast. 99% chance that memset runs faster than any hand-written memset16 which makes the whole question pointless.

If you want a 100% portable solution, before C11 there is none. Because there is no portable way to test alignment of a pointer. If it doesn't have to be 100% portable, you can use

char* p = malloc (size + 15);
p += (- (unsigned int) p) % 16;

This assumes that the alignment of a pointer is stored in the lowest bits when converting a pointer to unsigned int. Converting to unsigned int loses information and is implementation defined, but that doesn't matter because we don't convert the result back to a pointer.

The horrible part is of course that the original pointer must be saved somewhere to call free () with it. So all in all I would really doubt the wisdom of this design.


Viewing latest article 5
Browse Latest Browse All 18

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>