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

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

 



Hi Mercury,

>As far as I know, I can do new B[10]; and store it in any pointer type. ... No problem unless I try to dereference ptr, then I will get the wrong data.

Yes, that will work (in the sense "that will compile" and "that is allowed by the language specification").

Keep in mind that when you use an old C-style cast in that manner, you are lying to the compiler. The compiler trusts you, and will believe any lie you tell it.

But, please, don't be surprised if the code crashes when run. You are using a very sharp knife.

>I don't see this as lying to the compiler, just a clever use of casting and walking an array.

I don't think this is a clever use of casting -- I think that it is a dangerous use of casting. But, sometimes, that is what is needed, and why the language specification provides the facility.

>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?

As per your example.

>But then how would I delete the block?

delete[] block;
delete[] ptrarray;

>delete[] only appears to work when the pointer type matches the actual type allocated-- in contrast to 'delete', which works regardless.

Sort of correct. You are conflating a pointer-to-an-object as if it were the same thing as a pointer-to-an-array-of-objects. Even though they are both pointers, they are not the same thing.

Based on what you seem to be trying to do, only use new and delete, never use new[] and delete[], and you'll be fine.

HTH,
--Eljay


[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