Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy should I use malloc() when "char bigchar[ 1u << 31 - 1 ];" works just fine?
    primarykey
    data
    text
    <p>What's the advantage of using malloc (besides the NULL return on failure) over static arrays? The following program will eat up all my ram and start filling swap only if the loops are uncommented. It does not crash.</p> <p>...</p> <pre><code>#include &lt;stdio.h&gt; unsigned int bigint[ 1u &lt;&lt; 29 - 1 ]; unsigned char bigchar[ 1u &lt;&lt; 31 - 1 ]; int main (int argc, char **argv) { int i; /* for (i = 0; i &lt; 1u &lt;&lt; 29 - 1; i++) bigint[i] = i; */ /* for (i = 0; i &lt; 1u &lt;&lt; 31 - 1; i++) bigchar[i] = i &amp; 0xFF; */ getchar(); return 0; } </code></pre> <p>...</p> <p>After some trial and error I found the above is the largest static array allowed on my 32-bit Intel machine with GCC 4.3. Is this a standard limit, a compiler limit, or a machine limit? Apparently I can have as many of of them as I want. It will segfault, but only if I ask for (and try to use) more than malloc would give me anyway.</p> <p>Is there a way to determine if a static array was actually allocated and safe to use?</p> <p>EDIT: I'm interested in why malloc is used to manage the heap instead of letting the virtual memory system handle it. Apparently I can size an array to many times the size I think I'll need and the virtual memory system will only keep in ram what is needed. If I never write to e.g. the end (or beginning) of these huge arrays then the program doesn't use the physical memory. Furthermore, if I can write to every location then what does malloc do besides increment a pointer in the heap or search around previous allocations in the same process?</p> <p><strong>Editor's note:</strong> <code>1 &lt;&lt; 31</code> <a href="https://stackoverflow.com/questions/26192284/why-does-1-31-31-result-in-1/">causes undefined behaviour</a> if int is 32-bit, so I have modified the question to read <code>1u</code>. The intent of the question is to ask about allocating large static buffers.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload