there is some confusion regarding my code below.
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.
This code compiles and runs fine printing the expected string. I didn't expect it to as ptr was previously freed.
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.
Why does it work if I just pass the previously freed ptr as a parameter. It obviously allocates the memory again? Thanks in advance.
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.
#include <stdio.h>
#include <stdlib.h>
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;
}