title: Does malloc() use brk() or mmap()?
body: <p>c code:</p>
  
  <pre><code>// program break mechanism
  // TLPI exercise 7-1
  
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  void program_break_test() {
      printf("%10p\n", sbrk(0));
  
      char *bl = malloc(1024 * 1024);
      printf("%x\n", sbrk(0));
  
      free(bl);
      printf("%x\n", sbrk(0));
  
  }
  
  int main(int argc, char **argv) {
      program_break_test();
      return 0;
  }
  </code></pre>
  
  <p>When compiling following code:</p>
  
  <pre><code> printf("%10p\n", sbrk(0));
  </code></pre>
  
  <p>I get warning tip:</p>
  
  <p><code>format ‘%p’ expects argument of type ‘void *’, but argument 2 has type ‘int’</code></p>
  
  <p><strong>Question 1:</strong> Why is that?</p>
  
  <hr>
  
  <p>And after I <code>malloc(1024 * 1024)</code>, it seems the program break didn't change.</p>
  
  <p>Here is the output:</p>
  
  <pre><code>9b12000
  9b12000
  9b12000
  </code></pre>
  
  <p><strong>Question 2:</strong> Does the process allocate memory on heap when start for future use? Or the compiler change the time point to allocate? Otherwise, why?</p>
  
  <hr>
  
  <p><strong>[update] Summary: brk() or mmap()</strong></p>
  
  <p>After reviewing TLPI and check man page (with help from author of TLPI), now I understand how <code>malloc()</code> decide to use <code>brk()</code> or <code>mmap()</code>, as following:</p>
  
  <p><code>mallopt()</code> could set parameters to control behavior of <code>malloc()</code>, and there is a parameter named <code>M_MMAP_THRESHOLD</code>, in general:</p>
  
  <ul>
  <li>If requested memory is less than it, <code>brk()</code> will be used;</li>
  <li>If requested memory is larger than or equals to it, <code>mmap()</code> will be used;</li>
  </ul>
  
  <p>The default value of the parameter is <code>128kb</code> (on my system), but in my testing program I used 1Mb, so <code>mmap()</code> was chosen, when I changed requested memory to 32kb, I saw <code>brk()</code> would be used.</p>
  
  <p>The book mentioned that in TLPI page 147 and 1035, but I didn't read carefully of that part.</p>
  
  <p>Detailed info of the parameter could be found in man page for <code>mallopt()</code>.</p>