Can I free a pointer several times?
Or, can I free a pointer if I don't know whether it has been freed?
Can I free a pointer several times?
Or, can I free a pointer if I don't know whether it has been freed?
No. You must only free a pointer once, and only free pointers returned by a call to malloc(). (Or if it's some other memory allocation funtion: read the reference!)
For the C function free(), if you pass a pointer already free()'d or something not returned by malloc(), calloc(), or realloc(), you risk undefined behavior.
See malloc().
It is up to your program to keep track of what needs to be free()'d. An operating system should free any memory still allocated upon program termination. However, this doesn't mean you should just forget about freeing. Programs can eat memory quickly in a loop or after long runs. Personally, I try to free everything I allocate myself.
Last edited by Cactus_Hugger; 05-18-2006 at 11:10 PM.
long time; /* know C? */
Unprecedented performance: Nothing ever ran this slow before.
Any sufficiently advanced bug is indistinguishable from a feature.
Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
The best way to accelerate an IBM is at 9.8 m/s/s.
recursion (re - cur' - zhun) n. 1. (see recursion)
I concur. I always free everything I allocate myself. It is my opinion that if I ever am in the position where I cannot free something I've allocated, it's time to redesign, because I've really messed something up. If it's too hard to free what you've allocated, you're doing something wrong, IMO.
Quzah.
Hope is the first step on the road to disappointment.
Thanks. I've always learned much here.
You can set a pointer to NULL to indicate it has been freed.
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.
But setting it to NULL is not the same as freeing, at least not in C. dwks wasn't implying that, but for your clarification, I thought I'd point it out.
Quzah.
Hope is the first step on the road to disappointment.