best cross-platform method to get aligned memory

前端 未结 5 2027
梦谈多话
梦谈多话 2020-12-04 14:56

Here is the code I normally use to get aligned memory with Visual Studio and GCC

inline void* aligned_malloc(size_t size, size_t align) {
    void *result;
          


        
5条回答
  •  星月不相逢
    2020-12-04 15:08

    If you compiler supports it, C++11 adds a std::align function to do runtime pointer alignment. You could implement your own malloc/free like this (untested):

    template
    void *aligned_malloc(std::size_t size)
    {
        std::size_t space = size + (Align - 1);
        void *ptr = malloc(space + sizeof(void*));
        void *original_ptr = ptr;
    
        char *ptr_bytes = static_cast(ptr);
        ptr_bytes += sizeof(void*);
        ptr = static_cast(ptr_bytes);
    
        ptr = std::align(Align, size, ptr, space);
    
        ptr_bytes = static_cast(ptr);
        ptr_bytes -= sizeof(void*);
        std::memcpy(ptr_bytes, original_ptr, sizeof(void*));
    
        return ptr;
    }
    
    void aligned_free(void* ptr)
    {
        void *ptr_bytes = static_cast(ptr);
        ptr_bytes -= sizeof(void*);
    
        void *original_ptr;
        std::memcpy(&original_ptr, ptr_bytes, sizeof(void*));
    
        std::free(original_ptr);
    }
    

    Then you don't have to keep the original pointer value around to free it. Whether this is 100% portable I'm not sure, but I hope someone will correct me if not!

提交回复
热议问题