0

Regarding std::align:

void* align(size_t alignment, size_t size, void*& ptr, size_t& space)

Given a pointer ptr to a buffer [...] returns a pointer aligned by the specified alignment [...]. The function modifies the pointer [...]

If align is successful, then the returned pointer and ptr are the same.

This SO answer shows passing an offset address that leaves space for a pointer to align, storing the original pointer to the oversized chunk, and finally calling delete on the original pointer. Is that necessary, or is it safe to simply do this:

size_t space = 64;
void* ptr = malloc(space);
void* ret = std::align(alignment, targetSize, ptr, space);
if (ret == nullptr) { /* failed to align */ }
free(ptr);
Community
  • 1
  • 1
ZachB
  • 13,051
  • 4
  • 61
  • 89

1 Answers1

1

If the original pointer was misaligned there is no way for free() to determine the offset the result of std::align() added. Most likely the memory allocation algorithm will need to store some meta information with the allocation which can't be recovered in general.

You'll need to release the original pointer. I'm pretty sure passing a different pointer than the one originally obtained from malloc() and family in a call to free() yields undefined behaviour (likewise for other memory management facilities).

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • 1
    Note there are some allocation schemes where a pointer inside the allocated memory is sufficient; relying on that, even if it works, is not portable or reliable. – Yakk - Adam Nevraumont Mar 18 '17 at 18:00