Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding C malloc and sbrk()

Tags:

c

pointers

malloc

I am trying to understand the difference between malloc and sbrk in C and how they relate to each other. From what I understand malloc and sbrk are pretty much the same thing but I read that malloc uses sbrk in allocating memory. This is really confusing can someone explain it to me?

For example in this program does malloc call sbrk? if so does it simply call sbrk each time it gets called, so for this example 10 times?

int main(int argc, char **argv) {
        int i;
        void *start_pos, *finish_pos;
        void *res[10];
        start_pos = sbrk(0);
        for (i = 0; i < 10; i++) {
                res[i] = malloc(10);
        }
        finish_pos = sbrk(0);
        return 0;
}

Thank you,

like image 931
Free Lancer Avatar asked Jan 28 '26 06:01

Free Lancer


1 Answers

sbrk requests more memory from the operating system. It is a pretty low-level function and not very flexible.

malloc uses sbrk, but is more flexible. Generally, malloc will ask sbrk for large chunks of memory and then dole out pieces of those large chunks. So most calls to malloc will not result in calls to sbrk.

like image 55
rob mayoff Avatar answered Jan 30 '26 20:01

rob mayoff