_aligned_malloc
Visual Studio .NET 2003
Allocates memory on a specified alignment boundary.
void * _aligned_malloc( size_t size, size_t alignment );
Parameters
- size
- Size of the requested memory allocation.
- alignment
- The alignment value, which must be an integer power of 2.
Return Value
A pointer to the memory block that was allocated, or NULL if the operation failed.
Remarks
_aligned_malloc is based on malloc; see malloc for more information on using _aligned_malloc.
Requirements
| Routine | Required header | Compatibility |
|---|---|---|
| _aligned_malloc | <malloc.h> | Win 98, Win Me, Win NT, Win 2000, Win XP |
For additional compatibility information, see Compatibility in the Introduction.
Libraries
All versions of the C run-time libraries.
Example
// crt_aligned_malloc.c
#include <malloc.h>
#include <stdio.h>
int main() {
void *ptr;
size_t alignment, off_set;
// Note alignment should be 2^N where N is any positive int.
alignment = 16;
off_set = 5;
ptr = _aligned_malloc(100, alignment);
if ( ((int)ptr % alignment ) == 0 && ptr != NULL)
printf("This pointer, %d is aligned on %d\n", ptr, alignment);
else
printf("This pointer, %d is not aligned on %d\n",ptr, alignment);
ptr = _aligned_realloc(ptr, 200, alignment);
if ( ((int)ptr % alignment ) == 0)
printf("This pointer, %d is aligned on %d\n", ptr, alignment);
else
printf("This pointer, %d is not aligned on %d\n",ptr, alignment);
_aligned_free(ptr);
ptr = _aligned_offset_malloc(200, alignment, off_set);
if ( ( (((int)ptr) + off_set) % alignment ) == 0 && ptr != NULL)
printf("This pointer, %d is offset by %d on alignment of %d\n", ptr,
off_set, alignment);
else
printf("This pointer, %d is does not satisfy of offset %d and alignment %d\n",ptr, off_set, alignment);
ptr = _aligned_offset_realloc(ptr, 200, alignment, off_set);
if ( ( (((int)ptr) + off_set) % alignment ) == 0 && ptr != NULL)
printf("This pointer, %d is offset by %d on alignment of %d\n", ptr, off_set, alignment);
else
printf("This pointer, %d is does not satisfy of offset %d and alignment %d\n",ptr, off_set, alignment);
// Note that _aligned_free works for both _aligned_malloc
// and _aligned_offset_malloc. Using free is illegal.
_aligned_free(ptr);
}
Sample Output
This pointer, 3082224 is aligned on 16 This pointer, 3082224 is aligned on 16 This pointer, 3082219 is offset by 5 on alignment of 16 This pointer, 3082219 is offset by 5 on alignment of 16
See Also
Data Alignment | Run-Time Routines and .NET Framework Equivalents