Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In both cases, the cast is unnecessary and can mask errors; I'll delete the casts in the following. (<code>malloc()</code> returns a <code>void*</code>, which can be implicitly converted to a pointer-to-whatever.)</p> <pre><code>char **args = malloc(MAX_ARGS*sizeof(char*)); </code></pre> <p>This defined <code>args</code> as a pointer-to-pointer-to-char, and initializes it to point to a chunk of memory big enough to hold <code>MAX_ARGS</code> elements, each of which is a <code>char*</code>. Once you've done this, you'll want to assign values to those <code>char*</code> elements, likely making them point to strings.</p> <pre><code>char *args = malloc(MAX_ARGS*sizeof(char*)); </code></pre> <p>This is <em>legal</em>, but almost certainly a logical error. <code>args</code> is a pointer-to-char, which means it can point either to a single <code>char</code> object, or to the first element of an array of <code>char</code> elements. But you're allocating memory that can hold <code>MAX_ARGS</code> <em>pointers</em>.</p> <p>A more likely thing to do is:</p> <pre><code>char *s = malloc(MAX_LEN); </code></pre> <p>which will cause <code>s</code> to point to a region of memory that can hold <code>MAX_LEN</code> <code>char</code> elements (a string of length up to <code>MAX_LEN - 1</code>). (Note that <code>sizeof (char) == 1</code> by definition.)</p> <p>There's a useful trick to avoid type mismatches. A pointer of type <code>FOO*</code>, for any type <code>FOO</code>, needs to point to a chunk of memory big enough to old one or more elements of type <code>FOO</code>. If you write:</p> <pre><code>ptr = malloc(count * sizeof *ptr); </code></pre> <p>and <code>ptr</code> is a <code>FOO*</code>, then <code>sizeof *ptr</code> is the same as <code>sizeof (FOO)</code> -- but you won't have to update the line if you later change <code>ptr</code> to be a <code>pointer to</code>BAR`.</p> <p>In your case, the pointed-to type is itself a pointer, so you can write:</p> <pre><code>char **args = malloc(MAX_ARGS * sizeof *args); </code></pre> <p>And when you call <code>malloc</code>, you should <em>always</em> check whether it succeeded, and take some action if it failed -- even if that action is to terminate the program with an error message:</p> <pre><code>if (args == NULL) { fprintf(stderr, "malloc failed\n"); exit(EXIT_FAILURE); } </code></pre>
 

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