简体   繁体   中英

Program break doesnt change after calling malloc in a loop?

Running this piece of code is supposed to cause program break to increase by about malloc_counts * _SC_PAGESIZE instead I get fixed program break each time, so why is this. malloc is supposed to call brk or sbrk which itself round up size passed to next page (with some extra work). So what's happening ?

#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);
    }
}

which i guess of course using optimizations

Your compiler optimizes the calls to malloc out, because they are unused. Because malloc calls are removed, nothing changes and the heap is not moved.

And glibc overallocates a lot, so the value has to be large enough for it to see it. And the default M_MMAP_THRESHOLD seem to be128 * 1024 . So you have to pick a value large enough, but below mmap threshold to see a difference in glibc.

Disable your compiler optimizations and allocate a lot and heap will be moved. Try the following:

#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];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM