Search code examples
c++arraysdynamic-allocation

C++ delete[] void* curiosity


I've got a rather simple, though large, system setup. It stores it's data in a void* array because the data it's storing could vary between float or double depending on how much accuracy is needed.

just doing delete [] data raises a warning: deleting 'void*' is undefined [enabled by default] using MinGW. And I've got another variable to tell me if data is a float* or a double*, but does it matter which I use?

In other words, could I use the fallowing code without worrying about memory-leak's, or other errors/damage not caught by the compiler?

double* d_data = new double[length];
data = (void*)d_data;
delete [] (float*)data;

Solution

  • It certainly does matter; the pointer you use for delete[] must have the same type as the pointer that you allocated. So casting to double* is valid (but error-prone); casting to float* gives undefined behaviour.

    [There is an exception for single objects (not arrays) of class types - it can be a pointer to a base class, if that base class has a virtual destructor. But that doesn't apply to primitive types like double, or to arrays.]

    As for memory leaks: manual memory management always carries a danger of memory leaks, unless you're extremely careful never to do anything that might throw an exception. I highly recommend using RAII to manage all dynamic resources.