Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Ahhhh, no! That first call is not legal. You can't pass <code>realloc</code> some random pointer and hope for the best. The first parameter to realloc has to be either a pointer to memory that your program was previously allocated (through something like <code>malloc</code>, <code>calloc</code> or friends) or a null pointer.</p> <p>When <code>NULL</code> is passed, it's equivalent to <code>malloc</code>. The NULL call can be useful if you're re allocating in some kind of loop and don't want to have a special case the first time you allocate.</p> <hr> <p>While we're at it, the fairly standard ways to use malloc and realloc are:</p> <pre><code>int* p; p = malloc(10 * sizeof(int)); //Note that there's no cast //(also, it could just be int* p = malloc(...);) int* np = realloc(p, 15 * sizeof(int)); //Note that you keep the old pointer -- this is in case the realloc fails </code></pre> <hr> <p>As a tangential aside: history is the main reason you see declarations and assignments on different lines. In older versions of C, declarations had to come first in functions. That meant that even if your function didn't use a variable until 20 lines in, you had to declare at the top.</p> <p>Since you typically don't know what the value of a variable not used for another 20 lines should be, you can't always initialize it to anything meaningful, and thus you're left with a declaration and no assignment at the top of your function.</p> <p>In C99/C11, you do not have to declare variables at the top of scopes. In fact, it's generally suggested to define variables as close to their use as possible.</p>
 

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