Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h3>Original answer</h3> <pre><code>{ void *mem = malloc(1024+16); void *ptr = ((char *)mem+16) &amp; ~ 0x0F; memset_16aligned(ptr, 0, 1024); free(mem); } </code></pre> <h3>Fixed answer</h3> <pre><code>{ void *mem = malloc(1024+15); void *ptr = ((uintptr_t)mem+15) &amp; ~ (uintptr_t)0x0F; memset_16aligned(ptr, 0, 1024); free(mem); } </code></pre> <h3>Explanation as requested</h3> <p>The first step is to allocate enough spare space, just in case. Since the memory must be 16-byte aligned (meaning that the leading byte address needs to be a multiple of 16), adding 16 extra bytes guarantees that we have enough space. Somewhere in the first 16 bytes, there is a 16-byte aligned pointer. (Note that <code>malloc()</code> is supposed to return a pointer that is sufficiently well aligned for <em>any</em> purpose. However, the meaning of 'any' is primarily for things like basic types — <code>long</code>, <code>double</code>, <code>long double</code>, <code>long long</code>, and pointers to objects and pointers to functions. When you are doing more specialized things, like playing with graphics systems, they can need more stringent alignment than the rest of the system — hence questions and answers like this.)</p> <p>The next step is to convert the void pointer to a char pointer; GCC notwithstanding, you are not supposed to do pointer arithmetic on void pointers (and GCC has warning options to tell you when you abuse it). Then add 16 to the start pointer. Suppose <code>malloc()</code> returned you an impossibly badly aligned pointer: 0x800001. Adding the 16 gives 0x800011. Now I want to round down to the 16-byte boundary — so I want to reset the last 4 bits to 0. 0x0F has the last 4 bits set to one; therefore, <code>~0x0F</code> has all bits set to one except the last four. Anding that with 0x800011 gives 0x800010. You can iterate over the other offsets and see that the same arithmetic works.</p> <p>The last step, <code>free()</code>, is easy: you always, and only, return to <code>free()</code> a value that one of <code>malloc()</code>, <code>calloc()</code> or <code>realloc()</code> returned to you — anything else is a disaster. You correctly provided <code>mem</code> to hold that value — thank you. The free releases it.</p> <p>Finally, if you know about the internals of your system's <code>malloc</code> package, you could guess that it might well return 16-byte aligned data (or it might be 8-byte aligned). If it was 16-byte aligned, then you'd not need to dink with the values. However, this is dodgy and non-portable — other <code>malloc</code> packages have different minimum alignments, and therefore assuming one thing when it does something different would lead to core dumps. Within broad limits, this solution is portable.</p> <p>Someone else mentioned <code>posix_memalign()</code> as another way to get the aligned memory; that isn't available everywhere, but could often be implemented using this as a basis. Note that it was convenient that the alignment was a power of 2; other alignments are messier.</p> <p>One more comment — this code does not check that the allocation succeeded.</p> <h3>Amendment</h3> <p><a href="https://stackoverflow.com/users/23705/windows-programmer">Windows Programmer</a> pointed out that you can't do bit mask operations on pointers, and, indeed, GCC (3.4.6 and 4.3.1 tested) does complain like that. So, an amended version of the basic code — converted into a main program, follows. I've also taken the liberty of adding just 15 instead of 16, as has been pointed out. I'm using <code>uintptr_t</code> since C99 has been around long enough to be accessible on most platforms. If it wasn't for the use of <code>PRIXPTR</code> in the <code>printf()</code> statements, it would be sufficient to <code>#include &lt;stdint.h&gt;</code> instead of using <code>#include &lt;inttypes.h&gt;</code>. <em>[This code includes the fix pointed out by <a href="https://stackoverflow.com/users/832878/c-r">C.R.</a>, which was reiterating a point first made by <a href="https://stackoverflow.com/users/12943/bill-k">Bill K</a> a number of years ago, which I managed to overlook until now.]</em></p> <pre><code>#include &lt;assert.h&gt; #include &lt;inttypes.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; static void memset_16aligned(void *space, char byte, size_t nbytes) { assert((nbytes &amp; 0x0F) == 0); assert(((uintptr_t)space &amp; 0x0F) == 0); memset(space, byte, nbytes); // Not a custom implementation of memset() } int main(void) { void *mem = malloc(1024+15); void *ptr = (void *)(((uintptr_t)mem+15) &amp; ~ (uintptr_t)0x0F); printf("0x%08" PRIXPTR ", 0x%08" PRIXPTR "\n", (uintptr_t)mem, (uintptr_t)ptr); memset_16aligned(ptr, 0, 1024); free(mem); return(0); } </code></pre> <p>And here is a marginally more generalized version, which will work for sizes which are a power of 2:</p> <pre><code>#include &lt;assert.h&gt; #include &lt;inttypes.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; static void memset_16aligned(void *space, char byte, size_t nbytes) { assert((nbytes &amp; 0x0F) == 0); assert(((uintptr_t)space &amp; 0x0F) == 0); memset(space, byte, nbytes); // Not a custom implementation of memset() } static void test_mask(size_t align) { uintptr_t mask = ~(uintptr_t)(align - 1); void *mem = malloc(1024+align-1); void *ptr = (void *)(((uintptr_t)mem+align-1) &amp; mask); assert((align &amp; (align - 1)) == 0); printf("0x%08" PRIXPTR ", 0x%08" PRIXPTR "\n", (uintptr_t)mem, (uintptr_t)ptr); memset_16aligned(ptr, 0, 1024); free(mem); } int main(void) { test_mask(16); test_mask(32); test_mask(64); test_mask(128); return(0); } </code></pre> <p>To convert <code>test_mask()</code> into a general purpose allocation function, the single return value from the allocator would have to encode the release address, as several people have indicated in their answers.</p> <h3>Problems with interviewers</h3> <p><a href="https://stackoverflow.com/users/23072/uri">Uri</a> commented: Maybe I am having [a] reading comprehension problem this morning, but if the interview question specifically says: "How would you allocate 1024 bytes of memory" and you clearly allocate more than that. Wouldn't that be an automatic failure from the interviewer?</p> <p>My response won't fit into a 300-character comment...</p> <p>It depends, I suppose. I think most people (including me) took the question to mean "How would you allocate a space in which 1024 bytes of data can be stored, and where the base address is a multiple of 16 bytes". If the interviewer really meant how can you allocate 1024 bytes (only) and have it 16-byte aligned, then the options are more limited.</p> <ul> <li>Clearly, one possibility is to allocate 1024 bytes and then give that address the 'alignment treatment'; the problem with that approach is that the actual available space is not properly determinate (the usable space is between 1008 and 1024 bytes, but there wasn't a mechanism available to specify which size), which renders it less than useful.</li> <li>Another possibility is that you are expected to write a full memory allocator and ensure that the 1024-byte block you return is appropriately aligned. If that is the case, you probably end up doing an operation fairly similar to what the proposed solution did, but you hide it inside the allocator.</li> </ul> <p>However, if the interviewer expected either of those responses, I'd expect them to recognize that this solution answers a closely related question, and then to reframe their question to point the conversation in the correct direction. (Further, if the interviewer got really stroppy, then I wouldn't want the job; if the answer to an insufficiently precise requirement is shot down in flames without correction, then the interviewer is not someone for whom it is safe to work.)</p> <h3>The world moves on</h3> <p>The title of the question has changed recently. It was <em>Solve the memory alignment in C interview question that stumped me</em>. The revised title (<em>How to allocate aligned memory only using the standard library?</em>) demands a slightly revised answer — this addendum provides it.</p> <p>C11 (ISO/IEC 9899:2011) added function <code>aligned_alloc()</code>:</p> <blockquote> <p><strong>7.22.3.1 The <code>aligned_alloc</code> function</strong></p> <p><strong>Synopsis</strong> </p> <pre><code>#include &lt;stdlib.h&gt; void *aligned_alloc(size_t alignment, size_t size); </code></pre> <p><strong>Description</strong><br> The <code>aligned_alloc</code> function allocates space for an object whose alignment is specified by <code>alignment</code>, whose size is specified by <code>size</code>, and whose value is indeterminate. The value of <code>alignment</code> shall be a valid alignment supported by the implementation and the value of <code>size</code> shall be an integral multiple of <code>alignment</code>.</p> <p><strong>Returns</strong><br> The <code>aligned_alloc</code> function returns either a null pointer or a pointer to the allocated space.</p> </blockquote> <p>And POSIX defines <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_memalign.html" rel="noreferrer"><code>posix_memalign()</code></a>:</p> <blockquote> <pre><code>#include &lt;stdlib.h&gt; int posix_memalign(void **memptr, size_t alignment, size_t size); </code></pre> <p>DESCRIPTION</p> <p>The <code>posix_memalign()</code> function shall allocate <code>size</code> bytes aligned on a boundary specified by <code>alignment</code>, and shall return a pointer to the allocated memory in <code>memptr</code>. The value of <code>alignment</code> shall be a power of two multiple of <code>sizeof(void *)</code>.</p> <p>Upon successful completion, the value pointed to by <code>memptr</code> shall be a multiple of <code>alignment</code>.</p> <p>If the size of the space requested is 0, the behavior is implementation-defined; the value returned in <code>memptr</code> shall be either a null pointer or a unique pointer.</p> <p>The <code>free()</code> function shall deallocate memory that has previously been allocated by <code>posix_memalign()</code>.</p> <p>RETURN VALUE</p> <p>Upon successful completion, <code>posix_memalign()</code> shall return zero; otherwise, an error number shall be returned to indicate the error.</p> </blockquote> <p>Either or both of these could be used to answer the question now, but only the POSIX function was an option when the question was originally answered.</p> <p>Behind the scenes, the new aligned memory function do much the same job as outlined in the question, except they have the ability to force the alignment more easily, and keep track of the start of the aligned memory internally so that the code doesn't have to deal with specially — it just frees the memory returned by the allocation function that was used.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload