Skip to content
TheChatArchiveThe Chat Archive
o3-mini· OpenAIHugging Face LMArena Human Preference 140K

How do I allocate memory in C with a guaranteed alignment?

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with o4-mini-2025-04-16’s answer.
  1. User

    How do I allocate memory in C with a guaranteed alignment?

  2. Assistant

    In C11 you can use the standard function aligned_alloc(), which allocates memory with a specified alignment. For example:

    #include <stdlib.h>
    #include <stdio.h>
    
    int main(void) {
        size_t alignment = 16; // must be a power of two
        size_t size = 64;      // must be a multiple of alignment
    
        void *ptr = aligned_alloc(alignment, size);
        if (ptr == NULL) {
            perror("aligned_alloc failed");
            return EXIT_FAILURE;
        }
    
        // Use the allocated memory...
    
        free(ptr);
        return EXIT_SUCCESS;
    }
    

    Important notes when using aligned_alloc():

    • Alignment Must Be a Power of Two: The alignment argument should be a power of two.
    • Size Must be a Multiple of Alignment: The size parameter must be an integral multiple of alignment. This requirement may force you to allocate a slightly larger block than you initially need.

    Alternative Approaches

    If you are not working with C11 or if you need a portable solution on POSIX systems, consider using posix_memalign():

    #include <stdlib.h>
    #include <stdio.h>
    
    int main(void) {
        void *ptr;
        size_t alignment = 16; // Must be a multiple of sizeof(void*) as well.
        size_t size = 64;
    
        int err = posix_memalign(&ptr, alignment, size);
        if (err != 0) {
            fprintf(stderr, "posix_memalign failed: %d\n", err);
            return EXIT_FAILURE;
        }
    
        // Use the allocated memory...
    
        free(ptr);
        return EXIT_SUCCESS;
    }
    

    The posix_memalign() function does not impose the "size must be a multiple of alignment" requirement, which sometimes makes it more convenient.

    Windows

    If you are developing on Windows, you can use the _aligned_malloc() function:

    #include <malloc.h>
    #include <stdio.h>
    
    int main(void) {
        size_t alignment = 16;
        size_t size = 64;
    
        void *ptr = _aligned_malloc(size, alignment);
        if (ptr == NULL) {
            perror("_aligned_malloc failed");
            return EXIT_FAILURE;
        }
    
        // Use the allocated memory...
    
        _aligned_free(ptr);
        return EXIT_SUCCESS;
    }
    

    Using any of these methods will guarantee that the allocated memory is suitably aligned for your needs.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.