2

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,

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
Free Lancer
  • 1,000
  • 2
  • 16
  • 33

2 Answers2

9

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.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • 1
    It would probably just call it once, because you're allocating 10 blocks of 10 bytes each. Even with malloc's overhead, that's pretty small. The operating system can only hand out memory in multiples of 4096 bytes (on most systems). If you want to know for sure, run it under the debugger and put a breakpoint on sbrk. – rob mayoff Dec 13 '11 at 05:57
  • So I put a break point at sbrk as you said and it only called once. But isn't that wrong since I have 2 calls to sbrk? one for start and one for finish? – Free Lancer Dec 13 '11 at 06:02
  • So I placed a breakpoint at sbrk and it only broke once. Can the breakpoint check the code inside malloc? so that it breaks on the sbrk inside malloc – Free Lancer Dec 13 '11 at 06:24
3

malloc uses sbrk--a system call used to change the data segment K&R C has an appendix which walks through the implementation of malloc, free using the sbrk sys call.

vine'th
  • 4,890
  • 2
  • 27
  • 27