solidc
Robust collection of general-purpose cross-platform C libraries and data structures designed for rapid and safe development in C
Loading...
Searching...
No Matches
aligned_alloc.h
Go to the documentation of this file.
1
6#ifndef ALIGNED_ALLOC_H
7#define ALIGNED_ALLOC_H
8
9#include <stdalign.h>
10#include <stdbool.h>
11#include <stdlib.h>
12
13#ifdef __cplusplus
14extern "C" {
15#endif
16
17#if defined(_WIN32) || defined(__CYGWIN__)
18#include <malloc.h> // _aligned_malloc and _aligned_free
19#endif
20
21// Cross-platform aligned memory allocation
22static inline void* aligned_alloc_xp(size_t alignment, size_t size) {
23 // Alignment must be a power of two and at least sizeof(void*)
24 if ((alignment & (alignment - 1)) != 0 || alignment < sizeof(void*)) {
25 return NULL;
26 }
27
28#if defined(_WIN32) || defined(__CYGWIN__)
29 return _aligned_malloc(size, alignment);
30#else
31
32// Use standard C11 aligned_alloc where available
33#if __STDC_VERSION__ >= 201112L
34 return aligned_alloc(alignment, size);
35#else
36 // Fallback for older C standards
37 void* ptr = NULL;
38 if (posix_memalign(&ptr, alignment, size) != 0) {
39 return NULL;
40 }
41 return ptr;
42#endif
43#endif
44}
45
46// Cross-platform aligned memory deallocation
47static inline void aligned_free_xp(void* ptr) {
48#if defined(_WIN32) || defined(__CYGWIN__)
49 _aligned_free(ptr);
50#else
51 free(ptr);
52#endif
53}
54
55#define ALIGNED_ALLOC(alignment, size) aligned_alloc_xp(alignment, size)
56#define ALIGNED_FREE(ptr) aligned_free_xp(ptr)
57
58#ifdef __cplusplus
59}
60#endif
61
62#endif // ALIGNED_ALLOC_H