468,512 Members | 1,508 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,512 developers. It's quick & easy.

Null pointer check before calling free()?

I have a base class static character pointer d, which is called by 3 members in derived class in the following fashion

BaseClass::d = strdup(x);
//x is a character pointer whose value changes during execution.

Each time when this code is executed, character pointer d is overwritten and it cause memory leak. To prevent this memory leak, I want to call free(d) before strdup.
What will happen if free(d) is called when no memory is allocated to d(Initial case)?
How I can check if d is null pointer or not before calling free? Or is it safe to call free without this check?
Oct 13 '06 #1
1 10621
Banfa
9,056 Expert Mod 8TB
What will happen if free(d) is called when no memory is allocated to d(Initial case)?
How I can check if d is null pointer or not before calling free? Or is it safe to call free without this check?
If you call free(d) when d is not pointed at allocated memory you will get an exception and you program will crash.

Checking for a NULL pointer is easy

if (d == NULL)
{
}

but d will not automatically be NULL unless you set it to NULL somewhere.

It is not safe to free d without a check to see if it is actuall allocated so you code should be in the general case

Expand|Select|Wrap|Line Numbers
  1. if (d != NULL)
  2. {
  3.     free(d);
  4.     d = NULL;
  5. }
  6.  
The d = NULL; is a bit superflous if you are going to allocate more memory for it imediately but the point is that in the general case you need to set the pointer back to NULL after freeing it to make sure it isn't free'd again.
Oct 14 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

4 posts views Thread by Matthew | last post: by
16 posts views Thread by mike79 | last post: by
99 posts views Thread by Mikhail Teterin | last post: by
51 posts views Thread by Joe Van Dyk | last post: by
15 posts views Thread by jacob navia | last post: by
51 posts views Thread by atv | last post: by
76 posts views Thread by valentin tihomirov | last post: by
1 post views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.