Freeing memory before calling realloc()
<p>there is some confusion regarding my code below. </p>

<p>I allocate memory with malloc(), free it, then call realloc() with the same pointer ptr as the parameter, but don't use the return address from realloc.  </p>

<p>This code compiles and runs fine printing the expected string. I didn't expect it to as ptr was previously freed.</p>

<p>If I however assign the return address from realloc() to ptr instead, which is commented out, there are of course runtime errors as expected , as ptr will be NULL. </p>

<p>Why does it work if I just pass the previously freed ptr as a parameter. It obviously allocates the memory again? Thanks in advance.</p>

<p>NOTE: This code was wrote intentionally just to try and understand what is happening in the background. De-referencing a dangling pointer etc. of course is not recommended.</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

int main()
{
    char* ptr;
    ptr = (char*)malloc(20);

    strcpy(ptr, "Hello");

    printf("Address before free : %d\n", ptr);
    printf("%s\n", ptr);

    free (ptr);

    printf("Address after free  : %d\n", ptr);
    printf("%s\n", ptr);

    realloc(ptr, 30);

    //ptr = realloc(ptr, 30); // causes runtime problem as expected

    strcpy(ptr, "Hello");

    printf("Address after realloc  : %d\n", ptr);
    printf("%s\n", ptr);

    return 0;
}
</code></pre>