Segfault with delete[] operator & virtually derived classes
JP Mercury
swirlee@stickist.com
Mon Mar 7 17:43:00 GMT 2005
On Mon, 07 Mar 2005 13:44:07 +0000, Nathan Sidwell wrote
> JP Mercury wrote:
>
> > main() {
> > A *list = new B[10]; // Allocate 10x derived, store first in A *list
> this won't work. new B[10] gets you an array of 10 B objects, you can't
> expect that to look like an array of A objects.
Nathan,
Someone else made this comment too. But I am not treating 'list' like an array
of B's. For example, when I access the array I do:
instance_size = sizeof(B);
A *curptr = (A *) (((char *) list) + index*instance_size);
Then I have the index'th element in curptr.
As far as I have seen, this works and the only issue is in deleting. Perhaps
it is not pretty but I wanted to save the added overhead of storing an array
of pointers.
I have found a workaround that is clunky but works. If I declare a virtual
method in A and all derived classes:
virtual Killer() { delete[] this; };
And then do:
list->Killer();
It solves the problem. So I am using a virtual function to get around the
limitations of the delete[] operator.
Can you see other issues I might have overlooked?
Thanks Nathan,
Mercury
More information about the Gcc-help
mailing list