如何编写以下修改后的内存分配函数

How to write the following modified memory allocation function?

本文关键字:内存 分配 函数 修改 何编写      更新时间:2023-10-16

写一个对齐的malloc &自由函数,它接受字节数和对齐字节数(总是2的幂),并返回可被对齐字节数整除的内存地址。

Ex. align_malloc (1000,128);
it will return memory address multiple of 128 of the size 1000.
aligned_free(); 
it will free memory allocated by align_malloc.

对于分配函数,我编写了以下代码:

void * allocatemyfunc (size_t bytestobeallocated, size_t allignment)
{
  void * p1;
  void * p2;
  p1 = (void*)malloc(bytestobeallocated+allignment);
  if ( p1 == NULL )
    return 'error';
  else
  {
      size_t addr = bytestobeallocated + allignment;
      p2 = (void*)addr-(addr%allignment);
      return p2;
  }
}

这似乎是分配分配的合适解决方案。(我可能错了,如果我错了请纠正我)。

如何编写对齐的自由函数?(这基本上会释放所有分配的内存)

你的align malloc是错误的,你可以这样做来对齐指针。

uint8_t* ptr = (uint8_t*)malloc(N + alignment);
....
uint8_t offset = alignment - ((uintptr_t)ptr % alignment);
ptr += offset;

现在你有一个指针,它的前面有空闲空间的偏移字节,你把偏移量存储在那里。

*((uint8_t*)ptr - 1) = offset;

释放ptr,递减偏移量到开始

uint8_t offset = *((uint8_t*)ptr - 1);
free((uint8_t*)ptr - offset);

这不是一个确切的dup问题,但请参阅我在这里的答案以获得帮助

c++ 11中内存对齐的推荐方法是什么

方法是通过引用返回的内存

之前的内存,从返回的内存中找到块的开始。