free on new

R

robertwessel2

hi,

is it safe to call free on an object allocated by new.


No, absolutely not. On some implementations free might actually free
the memory, but there is *nothing* to require that behavior, and the
result may, in fact be catastrophic. But free will never call the
objects destructor (assuming it has one), and *that* may well be
fatal. The only things valid to pass to free() are what comes from
one of the malloc functions (malloc, realloc, calloc) or NULL, and
possibly some implementation specific extension. Objects new'd, must
be delete'd.
 
G

Goran

hi,

is it safe to call free on an object allocated by new.

No. Think e.g. about this: when you call new, you actually allocate
memory and call the constructor. When you call delete, you call the
destructor(s) and free memory. free() can't possibly call the
destructor(s) - it has no knowledge of what you are freeing. new/
delete pair do. Hence, they are paired and indispensable.

Goran.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top