Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can prevent them from crashing by not using them. :)</p> <p>In all seriousness, there is almost no safe way to use variable-length arrays to make your life easier unless you have strong bounds on the size. On the other hand, you can use them conditionally, in ways like this:</p> <pre><code>char vla_buf[n &lt; 1000 ? n : 1]; char *buf = sizeof vla_buf &lt; n ? malloc(n) : vla_buf; if (!buf) goto error; /* ... Do stuff with buf ... */ if (buf != vla_buf) free(buf); </code></pre> <p>While this looks like useless pain, it can make a huge performance difference, especially in threaded applications where many calls to <code>malloc</code> and <code>free</code> could result in lock contention. (A notable side benefit of this trick is that you can support old compilers without VLAs by simply replacing <code>[n &lt; 1000 ? n : 1]</code> with <code>1000</code>, e.g. with a macro.)</p> <p>Another obscure case where VLAs may be useful is in recursive algorithms where you know the total number of array entries required across all levels of recursion is bounded by <code>n</code>, where <code>n</code> is small enough you're confident it won't overflow the stack, but where there could be up to <code>n</code> levels of recursion and individual levels that use up to <code>n</code> elements. Prior to C99, the only way to handle this case without taking <code>n^2</code> stack space was to use <code>malloc</code>. With VLAs, you can solve the problem entirely on the stack.</p> <p>Keep in mind, these cases where VLAs are really beneficial are pretty damn rare. Normally VLA is just a way to deceive yourself that memory management is easy, until you get bit by the resulting (trivial-to-exploit) vulnerabilities you've created. :-)</p> <p><strong>Edit:</strong> To better address OP's original question:</p> <pre><code>#define MAX_VLA 10000 int bar(size_t n) { int arr[n &lt;= MAX_VLA ? n : 1]; if (sizeof arr/sizeof *arr &lt; n) return ENOMEM; /* ... */ return 0; } </code></pre>
    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.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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