So malloc doesn't invoke any syscall?

爱⌒轻易说出口 提交于 2020-01-11 05:13:06

问题


Related code:

  write(-1, "test", sizeof("test"));
  void * p = malloc(1024);
  void * p2 = malloc(510);
  write(-1, "hi", sizeof("hi"));

Related strace output:

write(4294967295, "test\0", 5)          = -1 EBADF (Bad file descriptor)
brk(0)                                  = 0x601000
brk(0x622000)                           = 0x622000
write(4294967295, "hi\0", 3)            = -1 EBADF (Bad file descriptor)

I'm surprised such low level operation doesn't involve syscall?


回答1:


Not every call to malloc invokes a syscall. On my linux desktop malloc allocates a space in 128KB blocks and then distributes the space. So I will see a syscall every 100-200 malloc calls. On freebsd malloc allocates by 2MB blocks. On your machine numbers will likely differ.

If you want to see syscall on every malloc allocate large amounts of memory (malloc(10*1024*1024*1024))




回答2:


What do you think brk is? malloc absolutely is invoking a syscall in this example, the syscall just isn't "malloc".




回答3:


malloc() calls the system brk() function (in Linux/Unix) - but it only calls it if the local heap is exhausted. I.e. most malloc implementations manage a memory heap obtained via brk(), and if it's too small or too fragmented they ask for more via brk().



来源:https://stackoverflow.com/questions/6326474/so-malloc-doesnt-invoke-any-syscall

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