1

运行这段代码应该会导致程序中断增加大约malloc_counts * _SC_PAGESIZE而不是我每次都得到固定的程序中断,所以这是为什么。malloc 应该调用brksbrk 将其本身向上舍入传递到下一页(需要一些额外的工作)。那么发生了什么?

#include <stdio.h>
#include <malloc.h>
#include <unistd.h>

int main(){
    const long malloc_counts = 10;
    printf("PAGE SIZE: %ld\n", sysconf(_SC_PAGESIZE));
    void* allocated_pool[malloc_counts];
    for(int counter=0; counter < malloc_counts; counter++)
    {
        printf("program brk: %p\n",sbrk(0));
        allocated_pool[counter] = malloc(127*4096);
    }
}
4

1 回答 1

2

我想当然是使用优化

您的编译器优化了对 out 的调用malloc,因为它们未被使用。因为malloc调用被删除,所以没有任何变化,堆也没有移动。

而且 glibc 过度分配了很多,所以值必须足够大才能看到它。默认值M_MMAP_THRESHOLD似乎是128 * 1024。所以你必须选择一个足够大但低于 mmap 阈值的值才能看到 glibc 的差异。

禁用编译器优化并分配很多,堆将被移动。尝试以下操作:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
    printf("PAGE SIZE: %ld\n", sysconf(_SC_PAGESIZE));
    #define malloc_counts  20
    void *allocated_pool[malloc_counts];
    for(int counter = 0; counter < malloc_counts; counter++) {
        printf("program brk: %p\n", sbrk(0));
        allocated_pool[counter] = malloc((size_t)127 * 1024);
        *(void *volatile *)&allocated_pool[counter];
    }
}
于 2020-09-14T19:48:10.020 回答