So malloc doesn't invoke any syscall?

前端 未结 3 1966
感情败类
感情败类 2021-01-12 17:44

Related code:

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


        
相关标签:
3条回答
  • 2021-01-12 18:27

    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().

    0 讨论(0)
  • 2021-01-12 18:44

    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))

    0 讨论(0)
  • 2021-01-12 18:49

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

    0 讨论(0)
提交回复
热议问题