Topic: extern "C" { char* strdup (const char*); }
Author: dima@Canine.CAD.UCLA.EDU (Dima Vasilyev)
Date: 15 Jan 93 21:09:01 GMT Raw View
Does anyone know, is it legal to use delete operator on character
strings, allocated in "C" environment? Example:
extern "C" {
char *strdup(const char *); // ANSI string.h
}
....
char *mystr = strdup("Something");
....
delete mystr;
....
Can it cause any harm?
Author: pjl@cs.uiuc.edu (Paul Lucas)
Date: Sat, 16 Jan 1993 01:14:18 GMT Raw View
In <9119@lee.SEAS.UCLA.EDU> dima@Canine.CAD.UCLA.EDU (Dima Vasilyev) writes:
>Does anyone know, is it legal to use delete operator on character
>strings, allocated in "C" environment? Example:
>extern "C" {
> char *strdup(const char *); // ANSI string.h
>}
>....
>char *mystr = strdup("Something");
>....
>delete mystr;
>....
>Can it cause any harm?
It's only guarenteed not to cause harm if that which is being
deleted was allocated by new (or the pointer is null).
--
- Paul J. Lucas
AT&T Bell Laboratories
Naperville, IL
Author: hansen@pegasus.att.com (Tony L. Hansen)
Date: Sat, 16 Jan 1993 08:12:42 GMT Raw View
< From: dima@Canine.CAD.UCLA.EDU (Dima Vasilyev)
< Does anyone know, is it legal to use delete operator on character strings,
< allocated in "C" environment? Example:
<
< extern "C" {
< char *strdup(const char *); // ANSI string.h
< }
< ....
< char *mystr = strdup("Something");
< ....
< delete mystr;
< ....
No, it's not legal.
strdup() is defined such that it returns a string allocated using malloc().
Values returned from malloc() must not be deallocated with delete.
Similarly, values returned from new must not be deallocated with free(). It
may happen to work on a few environments, but it certainly won't on many
others.
< Can it cause any harm?
Yes, it can lead to core dumps (or their moral equivalent) on many
environments.
----------------------------------------------------------------
Also, any values allocated as an array, as in
char *x = new char[50];
must be deallocated using delete[], as in
delete[] x;
Using delete instead of delete[] can also lead to core dumps (or their moral
equivalent) on some environments. It turns out that there are fewer
environments which will have problems with this, but it's still illegal.
Tony Hansen
hansen@pegasus.att.com, tony@attmail.com
att!pegasus!hansen, attmail!tony