如何编写以下修改后的内存分配函数
How to write the following modified memory allocation function?
写一个对齐的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中内存对齐的推荐方法是什么
方法是通过引用返回的内存
相关文章:
- Win32编译器选项和内存分配
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 当需要超过16GB的连续内存时,内存分配失败
- 尝试摆脱任何堆内存分配
- 以下代码执行哪种内存分配(动态或静态)?
- 开放 CV 中的动态内存分配,用于视频处理
- 为什么类和 main() 函数中也有动态内存分配
- 使用 NTAllocateVirtualMemory 和 GetProcAddress 的内存分配问题不起作用
- C++:矢量分配器行为、内存分配和智能指针
- 介于 [固定数组] 和 [带内存分配的指针] 之间的性能
- Linux C++ 中的页面对齐内存分配
- 整数内存分配/释放
- 将内存分配返回值强制转换为 TYPE 数组
- C++程序什么都不做,但瓦尔格林德显示内存分配
- 给定特定内存地址的数组的动态内存分配
- 如何完成内存分配
- 我刚刚了解了C++中的动态内存分配
- 在先前调用 string::find 后添加内存分配和内存集会导致它返回 npos.为什么?
- 对于堆上的页面对齐内存分配是否有任何优化或不同的 API?
- 无法删除布尔动态内存分配