How to allocate from heap with the correct memory alignment for InterlockedIncrement function?

This code seems to work, but have I used the InterlockedIncrement function correctly? The correct memory alignment of m_count is of my primary concern. Assume we're on a x86-64 system and compile a 64-bit application (in case that matters). By the way, for my actual purposes I can't declare m_count as a volatile long and then use InterlockedIncrement(&m_count); but it must be a pointer to data in heap.

#include <Windows.h>
#include <malloc.h>

class ThreadSafeCounter {
public:
    ThreadSafeCounter()
    {
        // Are those arguments for size and alignment correct?
        void* placement = _aligned_malloc( sizeof(long), sizeof(long) );
        m_count = new (placement) long(0);
    }
    ~ThreadSafeCounter()
    {
        _aligned_free( const_cast<long*>(m_count) );
    }

    void AddOne()
    {
        InterlockedIncrement(m_count);
    }

    long GetCount()
    {
        return *m_count;
    }

private:
    volatile long* m_count;
};

Answers


The heap allocator already aligns returned addresses to the native platform word size. 4 bytes for x86, 8 bytes for x64. You are using long, 32-bit on either platform for MSVC. No need to jump through the _aligned_malloc() hoop.


Need Your Help

Mongoid references_many ids array population

ruby-on-rails mongoid

I have a question regarding mongoid id storage for references_many.

Python - Setting / Getting Environment Variables and Addrs

python linux environment-variables

I need to set an environment variable in Python and find the address in memory where it is located. Since it's on Linux, I don't mind about using libraries that only work consistently on Linux (if ...