I am using std::aligned_alloc() in one of my projects to allocate aligned memory for optimized PCIe read/write.
When I read about aligned_alloc from here, it says:
Defined in header
<stdlib.h>
void *aligned_alloc( size_t alignment, size_t size );
Passing a size which is not an integral multiple of alignment or an alignment which is not valid or not supported by the implementation causes the function to fail and return a null pointer (C11, as published, specified undefined behaviour in this case, this was corrected by DR 460). Removal of size restrictions to make it possible to allocate small objects at restrictive alignment boundaries (similar to alignas) has been proposed by n2072.
From what I understood, now the only valid restriction is that the alignment parameter should be a valid alignment value (and a power of two). Fine. To get a valid alignment value, we can get the value of max_align_t.
[My System RAM - 128 GB. 2 CPUs - AMD EPYC 7313 16-Core Processor. It is a server machine running Centos7 latest]
I now have a couple of doubts here:
In my system, for almost every combination of 'alignment value' and 'size', aligned_alloc() returns success. (Unless the alignment is some huge value). How is this possible? Is it implementation specific?
My code snippet:
```
void* a = aligned_alloc(64, 524288000);
if(a == nullptr)
std::cout << "Failed" << std::endl;
else
std::cout << "Success" << std::endl;
```
Here is what values I tried for aligned_alloc() and their results:
aligned_alloc(64, 524288000) - Success
aligned_alloc(4096, 524288000) - Success
aligned_alloc(64, 331) - Success
aligned_alloc(21312323, 889998) - Success
aligned_alloc(1, 331) - Success
aligned_alloc(0, 21) - Success
aligned_alloc(21312314341, 331); - Success
aligned_alloc(21312312243413, 331); - Failed
Please do comment if any more info is needed to clear the question. Thanks