Understanding C malloc and sbrk()

余生颓废 提交于 2020-01-14 03:55:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!