By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,797 Members | 1,794 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,797 IT Pros & Developers. It's quick & easy.

free(0);

P: n/a
free(0);

is there a problem with this?

I try it with gcc, but there is no some kind of exception.

I wonder if this is accepted from standard C or it is a gcc protection rule.

This, work with delete a;, so I ask if work with free(a); too.

Because my code is full of:
if (a) { free(a); a = 0; }

Thanks
Feb 18 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
chameleon wrote:
free(0);

is there a problem with this?
No, it is legal.
--
Ian Collins.
Feb 18 '07 #2

P: n/a
s5n
On Feb 18, 11:36 pm, chameleon <cham_...@hotmail.comwrote:
free(0);

is there a problem with this?
....
This, work with delete a;, so I ask if work with free(a); too.

Because my code is full of:
if (a) { free(a); a = 0; }
Yes, there's a problem: free() is ONLY to be used with memory
allocated from malloc(). delete() is ONLY to be used to free up memory
allocated via one of the new() operators.

Also, it is legal to call free(0), according to the standard. Some old
code does a check (like the above) which only calls free(x) if x is
non-0, because historically (before the standard) some C libs would
crash if passed 0. According to the C++ standard, though, passing 0 to
free() or delete is a no-op.
Feb 18 '07 #3

P: n/a
chameleon wrote:
free(0);

is there a problem with this?
No. The function free() is inherited from C. Here is the relevant part of
the description (from a standard draft):
The free function causes the space pointed to by ptr to be deallocated,
that is, made available for further allocation. If ptr is a null pointer,
no action occurs. ...

[snip]
Best

Kai-Uwe Bux

BTW: you should consider using new/delete instead. In fact, you should
consider abandoning pointers in favor of higher order components such as
container classes provided by the standard library.
Feb 18 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.