问题
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,
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/8484863/understanding-c-malloc-and-sbrk