Program break doesnt change after calling malloc in a loop?

363 views Asked by At

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

There are 1 answers

2
KamilCuk On BEST ANSWER

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 be 128 * 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];
    }
}