gpt4 book ai didi

c - 内存分配阈值(mmap 与 malloc)

转载 作者:太空宇宙 更新时间:2023-11-04 08:02:38 27 4
gpt4 key购买 nike

我想指出我是新手,所以我会尽力理解/解释它。

我基本上是想弄清楚是否有可能由于我的项目的内存限制而将内存分配保持在阈值以下。

这是目前使用第三方 libsodium 分配内存的方式:

alloc_region(escrypt_region_t *region, size_t size)
{
uint8_t *base, *aligned;
#if defined(MAP_ANON) && defined(HAVE_MMAP)
if ((base = (uint8_t *) mmap(NULL, size, PROT_READ | PROT_WRITE,
#ifdef MAP_NOCORE
MAP_ANON | MAP_PRIVATE | MAP_NOCORE,
#else
MAP_ANON | MAP_PRIVATE,
#endif
-1, 0)) == MAP_FAILED)
base = NULL; /* LCOV_EXCL_LINE */
aligned = base;
#elif defined(HAVE_POSIX_MEMALIGN)
if ((errno = posix_memalign((void **) &base, 64, size)) != 0) {
base = NULL;
}
aligned = base;
#else
base = aligned = NULL;
if (size + 63 < size)
errno = ENOMEM;
else if ((base = (uint8_t *) malloc(size + 63)) != NULL) {
aligned = base + 63;
aligned -= (uintptr_t) aligned & 63;
}
#endif
region->base = base;
region->aligned = aligned;
region->size = base ? size : 0;

return aligned;
}

例如,这当前调用 posix_memalign 来分配(例如)32mb 内存。32mb 超过了给我的“内存上限”(但不会抛出内存警告,因为内存容量要大得多,这正是我“允许”使用的)

通过谷歌搜索,我觉得我可以使用 mmap 和虚拟内存。我可以看到上面的函数已经实现了一些 mmap,但从未被调用。

是否可以转换上面的代码,以便我永远不会超过我的 30mb 内存限制?

根据我的理解,如果这个分配会超过我的空闲内存,它会自动分配到虚拟内存中吗?那么我可以强制发生这种情况并假装我的可用空间低于可用空间吗?

感谢任何帮助

更新

/* Allocate memory. */
B_size = (size_t) 128 * r * p;
V_size = (size_t) 128 * r * N;
need = B_size + V_size;
if (need < V_size) {
errno = ENOMEM;
return -1;
}
XY_size = (size_t) 256 * r + 64;
need += XY_size;
if (need < XY_size) {
errno = ENOMEM;
return -1;
}
if (local->size < need) {
if (free_region(local)) {
return -1;
}
if (!alloc_region(local, need)) {
return -1;
}
}
B = (uint8_t *) local->aligned;
V = (uint32_t *) ((uint8_t *) B + B_size);
XY = (uint32_t *) ((uint8_t *) V + V_size);

最佳答案

I am basically trying to figure out if its possible to keep memory allocation under a threshold due to memory limitation of my project.

在 Linux 或 POSIX 系统上,您可以考虑使用 setrlimit(2)使用 RLIMIT_AS:

         This is the maximum size of the process's virtual memory
(address space) in bytes. This limit affects calls to brk(2),
mmap(2), and mremap(2), which fail with the error ENOMEM upon
exceeding this limit.

超过此限制,mmap 将失败,因此将失败,例如对 malloc(3) 的调用触发了 mmap 的特定使用。


I'm under the impression i can either use mmap

注意 malloc(3)会调用mmap(2) (或有时 sbrk(2) ...)从内核中检索(虚拟)内存,从而增加您的 virtual address space .但是,malloc 通常更喜欢重用以前 free-d 内存(如果可用)。而 free 通常不会调用 munmap(2)释放内存块,但更愿意为将来的 malloc-s 保留它。实际上,大多数 C 标准库将“小”和“大”分配区分开来(实际上,用于 1 GB 的 malloc 将使用 mmap,以及相应的 free 会立即 mmap

另见 mallopt(3)madvise(2) .如果您需要将某些页面(通过 mmap 获得)锁定到物理 RAM 中,请考虑 mlock(2) .

另请查看 this回答(解释特定进程使用的 RAM 的概念并不那么简单)。

对于 malloc 相关的错误(包括 memory leaks )使用 valgrind .

关于c - 内存分配阈值(mmap 与 malloc),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45036514/

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