Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!cs.utexas.edu!uunet!decwrl!sgi!shinobu!odin!xanadu.wpd.sgi.com!pal From: pal@xanadu.wpd.sgi.com (Anil Pal) Newsgroups: comp.std.c++ Subject: Re: delete [] p Message-ID: <1990Aug20.225638.18737@odin.corp.sgi.com> Date: 20 Aug 90 22:56:38 GMT References: <1990Aug16.162718.14828@sco.COM> <1231@lupine.NCD.COM> <1990Aug19.170256.21630@athena.mit.edu> <1253@lupine.NCD.COM> Sender: news@odin.corp.sgi.com (Net News) Reply-To: pal@xanadu.wpd.sgi.com (Anil Pal) Organization: Silicon Graphics, WorkGroup Products Division Lines: 78 Following up on the discussion of delete[], I wondered about virtual destructors, and whether they would be called correctly for arrays. To begin with, I was unable to find a definitive answer in the Annotated Reference Manual (although I may have missed it - please point me to it if I am wrong) as to whether or not Base * p = new Derived[10]; is legal, given class Derived : public Base; Assuming for the moment that it is (and my cfront 2.0 based translator does not complain, even with +p and +w enabled), then will delete [10] p (remember, this is 2.0, not 2.1) call the destructor for Derived, assuming Base::~Base is virtual? Well, I tried it, and yes, it did indeed call the derived destructor correctly. The next step was to invoke some other virtual function on each of the members of the array p. At this point things failed with a core dump. Now, I can understand that cfront has trouble determining the size of the elements in the array pointed to by p. My question is really why there is no warning whatsoever from the compiler for this situation, nor any prohibition that I could find against it in the ARM. Actually, this seems to be just another manifestation of C's confusion between arrays and pointers. Given that it is not possible to fix C, what can be done in C++? The simplest solution would be to prohibit Base *p = new Derived[20]; which would require differentiating between a pointer to Derived and a pointer to array of Derived. - Anil Pal Silicon Graphics pal@sgi.com (415)-335-7279 Attached is the program I used to test this. It compiles cleanly, but core dumps at run time on invoking the #include class Base { public: int i; virtual void print() { fprintf(stdout, "Base::print(%d)\n", i); } Base() {} virtual ~Base() { i = 0; } }; class Derived : public Base { public: int j; void print(); Derived() { j = 0; } ~Derived() { fprintf(stdout, "Derived::~Derived(%d)\n", i); } }; main() { Base* p = new Derived[20]; for (int i = 0 ; i < 20; ++i) { p[i].i = i; } /* This loop core dumps */ for (int j = 0 ; j < 20; ++j) { p[j].print(); } delete [20] p; return (0); }