Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You should make a distinction between <em>lost</em> and <em>still reachable</em> dynamic allocations (much like Valgrind does): If no more pointer to dynamic memory exists, then that memory is <em>lost</em>, and this should be considered a programming error, no matter whether this is in a loop and growing, or just a one off.</p> <p>On the other hand, if you allocate a couple of global resources and don't clean them up, then those are merely <em>still reachable</em>: You <em>could</em> free it if you wanted, but you just don't bother. That's a different issue, and while it may not be terribly elegant (and obscure debugging), it's also not the end of the world.</p> <p>Here's an example:</p> <pre><code>void * p, * q = malloc(100); for (int i = 0; i != 10; ++i) { p = malloc(15); } </code></pre> <p>In this situation, the memory at <code>q</code> is still reachable, and you could free it with <code>free(q);</code> at the end. On the other hand, nine out of ten allocations in the loop are <em>lost</em>, and you can never ever recover them.</p> <p>Here's how you might design something like a loop to be safe: make the convention that the pointer is always either NULL or valid.</p> <pre><code>void * p = 0; void free_it(void ** q) { free(*q); *q = NULL; } void make_something(void *q) { free_it(q); if (some_condition()) { q = malloc(100); } } int main() { p = malloc(25); // ... make_something(p); // ... free_it(p); // ... } </code></pre> <p>Basically, no matter whether you're currently holding dynamic memory or not, <code>p</code> will always accurately reflect that state, and anytime you want to allocate something new, you can safely free the previous pointer value, because it's either valid and needs to be freed or null.</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. 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