free()
int *bob
free(bob)
What would happen if i tried to free a pointer which isnt pointing anywhere yet?
Ye olde undefined behaviour. The C Standard allows anything to happen. Most likely your program will crash. Alternatively it may appear to do nothing. The behaviour may even change from one run of the program to another. Just don't do it!
Σnigma
Σnigma
It has undefined behavior. This can range from doing nothing to crashing your program to corrupting the heap.
Random behaviour or exception. The best thing to do is initialise the pointer then check it before you free it.
int *pTemp = 0;// Check if not NULLif(pTemp){ free(pTemp); pTemp = 0;}
There is never any need to check a pointer for nullness when using free, delete or delete[]. All three memory deallocation functions/operators are required to be equivalent to a no-op if passed a null pointer.
Σnigma
Σnigma
Quote:Original post by biscuitz
What would happen if i tried to free a pointer which isnt pointing anywhere yet?
"[It] could start a chain reaction that would unravel the very fabric of the space time continuum, and destroy the entire universe! Granted, that's a worse case scenario. The destruction might in fact be very localized, limited to our own galaxy."
Quote:Original post by biscuitz
so free(bob) wouldnt be horrible?
Uninitalized variables contain a random value (i.e. whatever was in memory at that location before). Assuming that they will be zero is a common, yet fatal, mistake.
Quote:Original post by biscuitz
so free(bob) wouldnt be horrible?
int * bob;free(bob);
is undefined.int * bob = 0;free(bob);
is perfectly fine.Σnigma
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement