gpt4 book ai didi

c - sbrk, malloc - 可以分配的最大内存

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:52:50 25 4
gpt4 key购买 nike

我想弄清楚可以使用 malloc() 为进程分配多少内存。

所以要点是:

start = sbrk(0);
malloc(1); /* so space is given to the data segment */
end = sbrk(0); /* start != end at this point */

/* Try to allocate in chunks as much as possible. */
while (end == sbrk(0)) {
malloc(1048576);

if (end == sbrk(0)){
maxMemory = maxMemory + 1048576;
}
}

return maxMemory;

所以我不明白的是:

如果你这样做:

start = sbrk(0);
malloc(1);
end = sbrk(0);

好的,结束!=开始

但是:

start = sbrk(0);
malloc(1048576);
end = sbrk(0);

开始==结束

所以,基本上,程序中断 (sbrk(0)) 不会随着较大的值移动。所以给定的 while 会持续很长时间,直到 sbrk(0) 被移动,我得到一个非常大的 Max 值 ~68gb。

我希望任何 malloc 最初都会移动数据段,但事实并非如此。有人可以解释为什么它没有(然后它在哪里分配?)和/或我做错了什么?

最佳答案

glibc malloc implementation使用 mmap() 分配更大的 block :

Normally, malloc() allocates memory from the heap, and adjusts the size of the heap as required, using sbrk(2). When allocating blocks of memory larger than MMAP_THRESHOLD bytes, the glibc malloc() implementation allocates the memory as a private anonymous mapping using mmap(2). MMAP_THRESHOLD is 128 kB by default, but is adjustable using mallopt(3). Allocations performed using mmap(2) are unaffected by the RLIMIT_DATA resource limit (see getrlimit(2)).

可以使用 mallopt() 调整此阈值通过设置 M_MMAP_THRESHOLD,但请注意,较新版本的库默认会动态调整此阈值:

Note: Nowadays, glibc uses a dynamic mmap threshold by default. The initial value of the threshold is 128*1024, but when blocks larger than the current threshold and less than or equal to DEFAULT_MMAP_THRESHOLD_MAX are freed, the threshold is adjusted upward to the size of the freed block. When dynamic mmap thresholding is in effect, the threshold for trimming the heap is also dynamically adjusted to be twice the dynamic mmap threshold. Dynamic adjustment of the mmap threshold is disabled if any of the M_TRIM_THRESHOLD, M_TOP_PAD, M_MMAP_THRESHOLD, or M_MMAP_MAX parameters is set.

关于c - sbrk, malloc - 可以分配的最大内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26699341/

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