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

后端 未结 3 1786
一生所求
一生所求 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 <unistd.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    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.

    0 讨论(0)
  • 2020-12-05 07:54

    malloc is not limited to using sbrk to allocate memory. It might, for example, use mmap to map a large MAP_ANONYMOUS block of memory; normally mmap will assign a virtual address well away from the data segment.

    There are other possibilities, too. In particular, malloc, being a core part of the standard library, is not itself limited to standard library functions; it can make use of operating-system-specific interfaces.

    0 讨论(0)
  • 2020-12-05 07:59

    If you use malloc in your code, it will call brk() at the beginning, allocated 0x21000 bytes from the heap, that's the address you printed, so the Question 1: the following mallocs requirements can be meet from the pre-allocated space, so these mallocs actually did't call brk, it is a optimization in malloc. If next time you want to malloc size beyond that boundary, a new brk will be called (if not large than the mmap threshold).

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