aligned memory allocation

本文介绍了一个用于内存对齐分配的 C 函数 `aligned_alloc` 和对应的释放函数 `aligned_free`。`aligned_alloc` 函数接收所需内存大小与对齐方式作为参数,并返回指向已对齐内存的指针;`aligned_free` 则用于释放由 `aligned_alloc` 分配的内存。
void *aligned_alloc(size_t size, size_t align) {
  void *p = NULL;
  void *ret = NULL;
  p = malloc(size + align + sizeof(void *));
  if (!p) return NULL;
  
  size_t offset = align - (size_t)p % align;
  if (offset < sizeof (void*)) offset += align;
  
  ret = (p + offset);
  *((size_t*)ret - 1) = (size_t)p;
  
  return ret;
}

void aligned_free(void *p) {
  free((void *)(*((size_t *)p - 1)));
}

#define MALLOC_CAP_EXEC (1<<0) ///< Memory must be able to run executable code #define MALLOC_CAP_32BIT (1<<1) ///< Memory must allow for aligned 32-bit data accesses #define MALLOC_CAP_8BIT (1<<2) ///< Memory must allow for 8/16/...-bit data accesses #define MALLOC_CAP_DMA (1<<3) ///< Memory must be able to accessed by DMA #define MALLOC_CAP_PID2 (1<<4) ///< Memory must be mapped to PID2 memory space (PIDs are not currently used) #define MALLOC_CAP_PID3 (1<<5) ///< Memory must be mapped to PID3 memory space (PIDs are not currently used) #define MALLOC_CAP_PID4 (1<<6) ///< Memory must be mapped to PID4 memory space (PIDs are not currently used) #define MALLOC_CAP_PID5 (1<<7) ///< Memory must be mapped to PID5 memory space (PIDs are not currently used) #define MALLOC_CAP_PID6 (1<<8) ///< Memory must be mapped to PID6 memory space (PIDs are not currently used) #define MALLOC_CAP_PID7 (1<<9) ///< Memory must be mapped to PID7 memory space (PIDs are not currently used) #define MALLOC_CAP_SPIRAM (1<<10) ///< Memory must be in SPI RAM #define MALLOC_CAP_INTERNAL (1<<11) ///< Memory must be internal; specifically it should not disappear when flash/spiram cache is switched off #define MALLOC_CAP_DEFAULT (1<<12) ///< Memory can be returned in a non-capability-specific memory allocation (e.g. malloc(), calloc()) call #define MALLOC_CAP_IRAM_8BIT (1<<13) ///< Memory must be in IRAM and allow unaligned access #define MALLOC_CAP_RETENTION (1<<14) ///< Memory must be able to accessed by retention DMA #define MALLOC_CAP_RTCRAM (1<<15) ///< Memory must be in RTC fast memory #define MALLOC_CAP_TCM (1<<16) ///< Memory must be in TCM memory #define MALLOC_CAP_DMA_DESC_AHB (1<<17) ///< Memory must be capable of containing AHB DMA descriptors #define MALLOC_CAP_DMA_DESC_AXI (1<<18) ///< Memory must be capable of containing AXI DMA descriptors #define MALLOC_CAP_CACHE_ALIGNED (1<<19) ///< Memory must be aligned to the cache line size of any intermediate caches #define MALLOC_CAP_INVALID (1<<31) ///< Memory can't be used / list end marker解析ESP32各内存
09-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值