Jens Åkerblom
Jens Åkerblom

Reputation: 908

Usage Issue of std::align

Consider the following code:

#include <memory>
#include <iostream>
#include <cstdio>

using namespace std;

// Visual Studio 2012 don't have alignof as a keyword.
#define alignof(type) __alignof(type) 

#define TEST_TYPE int

int main(int, char*[])
{
    TEST_TYPE i;
    void* pv = &i;
    size_t space = 100; // Just some big number.

    size_t alignment = alignof(TEST_TYPE);

    cout << "Alignment of int: " << alignment << endl;
    cout << "Is 'i' aligned: " 
         << (size_t(&i) % alignment == 0 ? "true" : "false" )
         << endl;

    if ( align(alignment, sizeof(TEST_TYPE), pv, space) )
    {
        TEST_TYPE* p = reinterpret_cast<TEST_TYPE*>(pv);

        cout << "Moved pointer " 
             << (size_t(p) - size_t(&i)) 
             << " bytes" 
             << endl;

        cout << "Is 'p' aligned: " 
             << (size_t(p) % alignment == 0 ? "true" : "false" )
             << endl;
    }
    else
    {
        cout << "Can't align 'i'" << endl;
    }

    return 0;
}

It creates an (properly aligned) integer and then calls std::align with the address of the integer. The output I get is:

Alignment of int: 4
Is 'i' aligned: true
Moved pointer 4 bytes
Is 'p' aligned: true

indicating that the pointer is moved, even though the address is already properly aligned. However, the documentation (http://en.cppreference.com/w/cpp/memory/align) says it "... modifies the ptr to point to the first possible address of such aligned storage..." but wouldn't that mean the pointer should be unchanged?

So my question: Will the third argument to std::align (the pointer) always be changed to be one size greater if the argument pointer already is aligned?

EDIT

Also, if the pointer is NOT changed then will not the example in http://www.cplusplus.com/reference/memory/align/?kw=align enter an infinite loop?

2nd EDIT

NOTE The link has been updated and the possible problem no longer occurs.

Upvotes: 3

Views: 2105

Answers (1)

Andrew Tomazos
Andrew Tomazos

Reputation: 68588

This looks like a bug in your standard library implementation, the output should be "Moved pointer 0 bytes" as pv is already aligned, so the first correctly aligned address in the range [pv,pv+100), is pv itself, not pv+4.

Although it does say in the standard:

The function updates its ptr and space arguments so that it can be called repeatedly with possibly different alignment and size arguments for the same buffer

I'm not sure exactley what this is saying, or if it is relevant. I don't think it is.

Upvotes: 2

Related Questions