C++ – Detecting Misusage of delete[] vs. delete at Compile Time

ccompilererror detection

I'd like to know if it's possible to detect the delete error commented below at compile time? Especially, I'd like to hear about g++ compiler.

ClassTypeA *abc_ptr = new ClassTypeA[100];  
abc_ptr[10].data_ = 1;  
delete abc_ptr; // error, should be delete []  

Best Answer

In general, the compiler can't detect such errors. Example: Suppose the constructor for some class allocates some data member using new TypeName[], but the destructor erroneously uses delete instead of delete[]. If the constructor and destructor are defined in separate compilation units, how is the compiler to know when compiling the file that defines the destructor that the usage is inconsistent with that in the separately compiled file that defines the constructor?

With regard to the GNU compilers, it doesn't. As noted above, it can't do so in the general case. A compiler doesn't have to detect such mismatched new/delete errors because this is undefined behavior. UB is the compiler vendor's "get out of jail free" card.

Tools such as valgrind can and do detect these kinds of new/delete mismatches, but do so at runtime. There might be a static analysis tool that looks at all of the source files that will eventually be compiled to form an executable, but I don't of any such static analysis tool that detect this kind of error.