Re: Segfault with delete[] operator & virtually derived classes

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Mercury,

  You might be interested in the new-placement optional argument to
the new operator.  It is defined in section 5.3.4 of the c++
specification.

corey


On Tue, 8 Mar 2005 12:14:22 -0700, JP Mercury <swirlee@xxxxxxxxxxxx> wrote:
> Nathan, Eljay, Lyle-
> 
> Thanks for your responses.
> 
> > >>you asked for an array of Bs, if you're not treating it as an array of
> > >>Bs it's not gonna work.
> 
> As far as I know, I can do new B[10]; and store it in any pointer type.
> For example:
> 
> char *ptr = (char *) new B[10];
> C *ptr = (C *) new C[10];
> 
> No problem unless I try to dereference ptr, then I will get the wrong data.
> But I take the true size of one array element into account and always cast
> back to a A * before dereferencing an array element. I don't see this as lying
> to the compiler, just a clever use of casting and walking an array.
> 
> I used to do a lot of video coding and we did that all the time, casting video
> memory between char * and long * and what not. The memory remains the same, we
> just look at it in a different way.
> 
> But let's say I take your suggestion and implement an array of pointers. How
> do I allocate the memory for 10 Bs in one block? I don't want 10 separate
> instances of B, I want a contiguous block of 10 Bs. I could create a block of
> 10 Bs:
> 
> B *block = new B[10];
> 
> and then an array of pointers:
> 
> A **ptrarray = new A *[10];
> 
> and then point the elements in the array to the block--
> 
> for (int i = 0; i < 10; i++)
>   ptrarray[i] = &block[i];  // Or block+i, whichever you prefer
> 
> But then how would I delete the block? I would still have to do:
> 
> delete[] block;
> 
> and I can't do this because in my code the memory manager (base class) does
> not know about the derived classes. delete[] only appears to work when the
> pointer type matches the actual type allocated-- in contrast to 'delete',
> which works regardless.
> 
> Kind Regards,
> -Mercury
> 
>

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux