Start of change

aligned_alloc() — Allocating aligned memory blocks

Standards

Standards / Extensions C or C++ Dependencies
C11 both  

Format

#include <stdlib.h>
void *aligned_alloc( size_t alignment, size_t size );

General description

The aligned_alloc function allocates space for an object whose alignment is specified by alignment, whose size is specified by size, and whose value is indeterminate.

Special behavior for C++: The C++ keywords new and delete are not interoperable with aligned_alloc(), calloc(), free(), malloc(), or realloc().
Note: To use the aligned_alloc() function, compile the source code with the LANGLVL(EXTC1X) option.

Parameters

alignment
Specifies the alignment. The value of alignment is a power of two.
Note: AMODE 31 supports up to 8 bytes alignment while AMODE 64 supports up to 16 bytes alignment.
size
Number of bytes to allocate. The value of size is an integral multiple of alignment.

Returned Value

On success, returns the pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated with free() or realloc().

On failure, returns a null pointer, it sets errno to one of the following values:

Error Code
EINVAL

The value of alignment is not supported.

ENOMEM
Insufficient memory is available

Example

CELEBM26
/* CELEBM26                                      
This example prompts you allocate size (which is an integral multiple of alignment) bytes of uninitialized storage. 
If &aligned_alloc was successful, the example prints the address returned; otherwise, it prints errno.
*/     
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
 
int main(void)
{ 
int *p1 = aligned_alloc(8, 8*sizeof *p1);
if(!p1)
{
printf("aligned_alloc failed with errno = %d\n", errno);
return -1;
}
else
{
    printf("8-byte aligned addr: %p\n", (void*)p1);
        free(p1);
}
return 0;
}

Output

One possible output is:
8-byte aligned addr: 22575D20

Related information

End of change