How to check if a pointer points to a properly aligned memory location?

后端 未结 1 1618
天涯浪人
天涯浪人 2021-02-06 23:33

Given a void * to some storage, how to check whether it points to properly aligned storage without any implementation defined behavior?

Of course we have st

相关标签:
1条回答
  • 2021-02-07 00:19

    If the remainder isn't zero when dividing the address with the desired alignment, then the address isn't aligned.

    inline bool
    is_aligned(const void * ptr, std::uintptr_t alignment) noexcept {
        auto iptr = reinterpret_cast<std::uintptr_t>(ptr);
        return !(iptr % alignment);
    }
    

    Ths can't be constexpr though, because of the cast.

    Also, this relies on the implementation-defined fact that the conversion from pointer to integer must preserve the numeric representation of the address. As pointed out by the comments, that is not guaranteed by the standard, so this function is not necessarily portable to all platforms. That is also true, because it is optional for the implementation to provide std::uintptr_t.


    I would expect this to only be needed when aligning for a type, so this might be more convenient:

    template<class T>
    bool
    is_aligned(const void * ptr) noexcept {
        auto iptr = reinterpret_cast<std::uintptr_t>(ptr);
        return !(iptr % alignof(T));
    }
    
    0 讨论(0)
提交回复
热议问题