free()

Started by
12 comments, last by Code Fusion 17 years, 10 months ago
int *bob free(bob) What would happen if i tried to free a pointer which isnt pointing anywhere yet?
Advertisement
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
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;}

Steven Yau
[Blog] [Portfolio]

End of world ... possibly ... (falls undefined behaviour)

"I can't believe I'm defending logic to a turing machine." - Kent Woolworth [Other Space]

ty for code yaustar :)
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
so free(bob) wouldnt be horrible?
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.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
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