Does malloc() use brk() or mmap()?

后端 未结 3 1803
一生所求
一生所求 2020-12-05 07:19

c code:

// program break mechanism
// TLPI exercise 7-1

#include 
#include 

void program_break_test() {
    printf(\"%10p\\n         


        
3条回答
  •  感情败类
    2020-12-05 07:39

    If we change the program to see where the malloc'd memory is:

    #include 
    #include 
    #include 
    
    void program_break_test() {
      printf("%10p\n", sbrk(0));
    
      char *bl = malloc(1024 * 1024);
      printf("%10p\n", sbrk(0));
      printf("malloc'd at: %10p\n", bl);
    
      free(bl);
      printf("%10p\n", sbrk(0));
    
    }
    
    int main(int argc, char **argv) {
      program_break_test();
      return 0;
    }
    

    It's perhaps a bit clearer that sbrk wouldn't change. The memory given to us by malloc is being mapped into a wildly different location.

    You could also use strace on Linux to see what system calls are made, and find out that malloc is using mmap to perform the allocation.

提交回复
热议问题