Reputation: 11948
int main()
{
int *ptr, **ptr1;
ptr = (int*)malloc(sizeof(int));
ptr1 = (int**)malloc(sizeof(int));
free(ptr);
*ptr = 12345;
ptr1 = &ptr;
//free(ptr);
//**ptr1 = 23456;
printf("%d \n", **ptr1);
system("pause");
return 0;
}
How does *ptr
store the value 12345
, when the memory has already been freed
? So, now ptr
should be pointing to garbage
.
Why is this happening?
Upvotes: 3
Views: 203
Reputation: 9354
You seem not to understand undefined behaviour. Basically, the behaviour is undefined. It could do anything, including (but not limited to) the following:
Accessing freed memory in general is likely (on most systems) to appear as though it has worked, whilst randomly corrupting data that some other part of the program thinks it owns (depending if there's been an alloc after the free).
Attempting to define undefined behaviour is putting you on a hiding to nothing. It's much better just not to do it in the first place.
Upvotes: 1
Reputation: 307
free() releases the memory pointed to by *ptr but does not change the value of *ptr so if that value does not conflict with anything else it will still work, but the memory may be allocated by another process at random. Common practice is to do free(ptr); ptr = NULL to avoid accidental reuse of the memory without another malloc call.
Upvotes: 0
Reputation: 57764
The pointer is freed, but it still points whereever it did when it was allocated. It is considered a serious programming error to do this. But the run time environment does not (normally) help identify or correct such errors.
Do not point the gun at yourself and pull the trigger!
Upvotes: 4
Reputation: 399703
This code is just so very wrong, on so many levels.
malloc()
in C.ptr1
needs sizeof *ptr1
, not sizeof (int)
. It's a pointer!malloc()
might fail. Check the return value before using it.free()
d it. Undefined behavior.Also, note that the pointer itself is not destroyed when you call free()
on it; the thing that goes away is the memory the pointer refers to. So you can still store a pointer's worth of bits in the pointer itself, if you like. There are rarely cases when this is needed though, and care should be taken when/if you inspect the bits.
Upvotes: 8
Reputation: 258548
That's undefined behavior, anything can happen.
free(ptr);
*ptr = 12345;
Is illegal. It can crash or, if you're unlucky, it can appear to work, potentially hiding the problem until the software is shipped to a nuclear power plant. Although, if you're writing code like this, you're probably not working for such companies. :)
Upvotes: 3