Jump to content
  • Advertisement
Sign in to follow this  
biscuitz

free()

This topic is 4541 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
It has undefined behavior. This can range from doing nothing to crashing your program to corrupting the heap.

Share this post


Link to post
Share on other sites
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 NULL
if(pTemp)
{
free(pTemp);
pTemp = 0;
}


Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!