function
<memory>

std::align

void* align (size_t alignment, size_t size, void*& ptr, size_t& space);
Align in range
Returns a pointer to the first possible address of the range of space bytes pointed by ptr where it is possible to fit size bytes of storage aligned as specified by alignment.

The function updates ptr to point to such address, and decreases space by the number of bytes used for alignment, so that these arguments can be used in repeated calls to this function.

If space is not enough to accommodate for the requested aligned buffer, the function returns a null pointer, and alters neither ptr nor space.

Parameters

alignment
Requested alignment, in bytes.
This shall be a valid alignment value supported by the platform in this context.
size_t is an unsigned integral type.
size
Size of the element to be aligned, in bytes.
size_t is an unsigned integral type.
ptr
Pointer to contiguous storage of at least space bytes.
This argument, passed by reference, is updated by the function.
space
Maximum size of the buffer to consider for alignment.
This argument, passed by reference, is updated by the function.
size_t is an unsigned integral type.

Return value

If the aligned buffer fits into the proposed space, the function returns the updated value of ptr. Otherwise, a null pointer is returned.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// align example
#include <iostream>
#include <memory>

int main() {
  char buffer[] = "------------------------";
  void * pt = buffer;
  std::size_t space = sizeof(buffer)-1;
  while ( std::align(alignof(int),sizeof(char),pt,space) ) {
    char* temp = static_cast<char*>(pt);
    *temp='*'; ++temp; space-=sizeof(char);
    pt=temp;
  }
  std::cout << buffer << '\n';
  return 0;
}


Possible output:
-*---*---*---*---*---*--

See also