gpt4 book ai didi

c++ - 是否有相当于 _aligned_realloc 的 linux

转载 作者:行者123 更新时间:2023-12-03 06:51:30 24 4
gpt4 key购买 nike

是否有 linux 等效于 _aligned_realloc ?
我想使用 realloc 所以我不必每次调整数据时都对数据进行 memcpy。我被 mmap 卡住了吗?我只使用了一次 mmap 是否有推荐的方法来实现将调整几次大小的内存?我假设我不能将 mmap 与aligned_alloc 混合使用,并且我必须在第一次调整大小时执行memcpy? (或始终使用 mmap)
下面的 realloc 并不总是对齐。我在(64位)linux下使用gcc和clang进行了测试

#include<cstdlib>
#include<cstdio>
#define ALIGNSIZE 64
int main()
{
for(int i = 0; i<10; i++)
{
void *p = aligned_alloc(ALIGNSIZE, 4096);
void *p2 = realloc(p, 4096+2048); //This doesn't always align
//void *p3 = aligned_alloc(ALIGNSIZE, 4096/24); //Doesn't need this line to make it unaligned.

if (((long)p & (ALIGNSIZE-1)) != 0 || ((long)p2 & (ALIGNSIZE-1)) != 0)
printf("%d %d %d\n", i, ((long)p & (ALIGNSIZE-1)) != 0, ((long)p2 & (ALIGNSIZE-1)) != 0);
}
}

最佳答案

不,在 C++、POSIX 标准和 GNU C 库中都没有标准替代方案。
这是仅使用标准函数的概念证明:

void*
aligned_realloc_optimistic(
void* ptr, std::size_t new_size, std::size_t alignment)
{
void* reallocated = std::realloc(ptr, new_size);
return is_aligned(reallocated, alignment) // see below
? reallocated
: aligned_realloc_pessimistic(reallocated, new_size, new_size, alignment);
// see below
}
正如评论中指出的:这有一个警告,在最坏的情况下 std::realloc可能无法重用 allcation 并且碰巧返回一个未对齐的指针,然后我们分配两次。
我们可以通过无条件分配、复制和释放来跳过重新分配的尝试,这消除了双重分配的最坏情况和无分配的最佳情况:
void*
aligned_realloc_pessimistic(
void* ptr, std::size_t new_size, std::size_t old_size, std::size_t alignment)
{
void* aligned = std::aligned_alloc(alignment, new_size);
std::memcpy(aligned, ptr, old_size);
std::free(ptr);
return aligned;
}
这样做的明显问题是我们必须知道常规重新分配不需要的旧大小。
依靠系统特定的函数,我们可以保持避免分配和避免双重分配的最佳情况,并且不需要知道旧的大小:
void*
aligned_realloc_glibc(
void* ptr, std::size_t new_size, std::size_t alignment)
{
auto old_size = malloc_usable_size(ptr); // GNU extension
return old_size >= new_size && is_aligned(ptr, alignment)
? ptr
: aligned_realloc_pessimistic(ptr, new_size, old_size, alignment);
}
上面使用的辅助函数:
bool is_aligned(void* ptr, std::size_t alignment)
{
std::size_t space = 1;
return std::align(alignment, space, ptr, space);
}

关于c++ - 是否有相当于 _aligned_realloc 的 linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64884745/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com