Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm a little horrified by all the recommendations for a goto statement!</p> <p>I have found that the use of goto leads to confusing code which is more likely to give rise to programmer errors. My preference now is to avoid its use altogether, except in the most extreme situations. I'd almost never use it. Not because of academic perfectionism, but because a year or more later it always seems more difficult to recall the overall logic than with the alternative I will suggest.</p> <p>Being one who loves to refactor things to minimize my option to forget stuff (like clearing a pointer), I'd add a few functions first. I'll presume it's likely that I would be reusing these quite a bit in the same program. Function imalloc() would do the malloc operation with the indirect pointer; ifree() would undo this. cifree() would free memory conditionally.</p> <p>With that in hand, my version of the code (with a third arg, for sake of demonstration) would be like this:</p> <pre><code>// indirect pointer malloc int imalloc(void **mem, size_t size) { return (*mem = malloc(size)); } // indirect pointer free void ifree(void **mem) { if(*mem) { free(*mem); *mem = NULL; } } // conditional indirect pointer free void cifree(int cond, void **mem) { if(!cond) { ifree(mem); } } int func(void **mem1, void **mem2, void **mem3) { int result = FALSE; *mem1 = NULL; *mem2 = NULL; *mem3 = NULL; if(imalloc(mem1, SIZE)) { if(imalloc(mem2, SIZE)) { if(imalloc(mem3, SIZE)) { result = TRUE; } cifree(result, mem2); } cifree(result, mem1); } return result; } </code></pre> <p>I prefer to have only one return from a function, at the end. Jumping out in between is quick (and in my opinion, kind of dirty). But more significantly, allows you to easily bypass associated cleanup code unintentionally.</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.
    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.
 

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