Jerry Coffin
re: Can I use delete with malloc'ed items?
In article <MPG.1a034610a6f41385989680@news.westnet.com.au> , mirror@
127.0.0.1 says...[color=blue]
> I knoew that free is usually paired with malloc and delete is usually
> paired with malloc, alloc or similar.[/color]
No -- free is paired with malloc or calloc. delete is paired with new,
and delete[] with new[].
[color=blue]
> Can I use delete with malloc?[/color]
If you do so, you'll get undefined behavior. Experience indicates that
this particular undefined behavior will NOT be innocuous either -- it
will lead to nasty misbehavior in a lot of cases.
[color=blue]
> The main reason I ask is for using the
> strdup function. If I have a char *, I have no real way of knowing
> whether that char * had memory allocated for it using new or malloc (as
> used by strdup).[/color]
strdup isn't standard, so it's impossible to say for sure, but every
version of it I've seen has used malloc.
Having said that, I feel obliged to question using strdup in C++ at all.
Use std::string, and it handles these sorts of things automatically.
--
Later,
Jerry.
The universe is a figment of its own imagination. |