Path: utzoo!utgpu!watserv1!watmath!att!cbnewsk!hansen From: hansen@pegasus.att.com (Tony L. Hansen) Newsgroups: comp.std.c++ Subject: Re: Proposed addition to string library: strnew Summary: diff between new() and malloc() Message-ID: <1990Sep13.161933.3676@cbnewsk.att.com> Date: 13 Sep 90 16:19:33 GMT References: <2699@dataio.Data-IO.COM> Sender: hansen@cbnewsk.att.com (tony.l.hansen) Organization: AT&T Bell Laboratories Lines: 29 In article <2699@dataio.Data-IO.COM>, bright@Data-IO.COM (Walter Bright) writes: < In article fox@research.att.com (David Fox) writes: << I propose the following function be added to the standard string.h: << inline char * strnew(const char *s) { << return s ? strcpy(new char[strlen(s)+1], s) : 0; << } < < What's the matter with strdup()? It's not ANSI C, but it's in common < usage among MS-DOS and OS/2 compilers. strdup() is defined as using malloc() underneath. However, there's no guarantee in any of the C++ books that new[] and malloc() must be compatible in any way. In other words, you cannot assume that you can create a value using new[] and then use free() on it later, or create a value using malloc() and pass it to delete later. It's guaranteed that new[] is NOT compatible for types with a constructor or destructor, as new[] is required to keep track of the number of members within the array. Some implementations of new[] may use malloc(), but allocate a larger amount of memory, and then place the number of members in front of the memory whose pointer is returned. Such an implementation is DEFINITELY NOT compatible with malloc(). Whether this is done for all invocations of new[], or just those for types without constructors/destructors, is implementation dependent. Consequently, you cannot guarantee anything for any invocations of new[]. Tony Hansen att!pegasus!hansen, attmail!tony hansen@pegasus.att.com