What happens when you call malloc on an existing variable?
<p>If a variable was already <code>malloc</code>'ed in the past, what happens if you call <code>malloc</code> on it again rather than <code>realloc</code>? Will it cause a memory leak?</p>

<p>I'd like to know so that I can add checks before <code>malloc</code> calls on parameters passed to functions in order to avoid potential leaks.</p>

<pre><code>void memtest(char **foo)
{
        if ( foo )
                *foo = malloc(10); // Assuming *foo was already allocated in the past.
}
</code></pre>

<p>Should I always do the following?</p>

<pre><code>void memtest(char **foo)
{
        if ( foo ) {
                if ( *foo ) {
                        free(*foo);

                        *foo = NULL;
                }

                *foo = malloc(10);
        }
}
</code></pre>