Files

79 lines
2.0 KiB
C
Raw Permalink Normal View History

2026-08-10 01:21:15 +08:00
#ifndef INCLUDED_C_MEMORY_H
#define INCLUDED_C_MEMORY_H
#ifndef INCLUDED_STDLIB_H
#define INCLUDED_STDLIB_H
#include <stdlib.h>
#endif /*INCLUDED_STDLIB_H*/
#ifndef INCLUDED_C_BASE_H
#include <c_Base.h>
#endif /*INCLUDED_C_BASE_H*/
#ifndef INCLUDED_C_ALIGNMENT_H
#include <c_Alignment.h>
#endif /*INCLUDED_C_ALIGNMENT_H*/
/* ------------------------------------------------------------------------------------------------------------------ */
/* */
C_STATIC_FORCE_INLINE
void* c_Memory_Alloc(c_size_t size) {
return malloc(size);
}
C_STATIC_FORCE_INLINE
void* c_Memory_Realloc(void* ptr, c_size_t size) {
return realloc(ptr, size);
}
C_STATIC_FORCE_INLINE
void* c_Memory_Calloc(c_size_t count, c_size_t size) {
return calloc(count, size);
}
C_STATIC_FORCE_INLINE
void c_Memory_Free(void* ptr) {
if (ptr) free(ptr);
}
C_STATIC_FORCE_INLINE
void* c_Memory_AlignedAlloc(c_size_t size, c_size_t alignment) {
#if defined(_MSC_VER) || defined(__MINGW32__)
// Windows 環境下使用微軟特有的對齊配置函數
return _aligned_malloc(size, alignment);
#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
// 真正的 C11 環境,且支援 aligned_alloc
return aligned_alloc(alignment, size);
#else
// POSIX 環境 (Linux/macOS) 的備用方案
void* ptr = NULL;
if (posix_memalign(&ptr, alignment, size) != 0) return NULL;
return ptr;
#endif
}
C_STATIC_FORCE_INLINE
void c_Memory_AlignedFree(void* ptr) {
#if defined(_MSC_VER) || defined(__MINGW32__)
_aligned_free(ptr);
#else
free(ptr);
#endif
}
/* ------------------------------------------------------------------------------------------------------------------ */
/* */
#define C_ALLOC(n) c_Memory_Alloc(n)
#define C_REALLOC(p, n) c_Memory_Realloc((p), (n))
#define C_CALLOC(x, n) c_Memory_Calloc((x), (n))
#define C_FREE(p) do{if(p){c_Memory_Free(p); (p)=NULL;}}while(0)
#define C_RESIZE(p, n) (p)=C_REALLOC(p, n)
#define C_NEW(p) (p)=C_ALLOC(sizeof(*(p)))
#define C_NEW0(p) (p)=C_CALLOC(1, sizeof(*(p)))
#endif /*INCLUDED_C_MEMORY_H*/