Here is synthetic example of using custom delete(...) operator overload for a separate class. I am constructing object of class String by allocating memory with std::malloc(...) followed by placement new(...) String. Also i declare custom delete operator for class String that is supposed to use std::free(...) inside it's definition. I know that it is illegal to delete pointers not allocated with new. But
#include <memory>
#include <cstdlib>
#include <utility>
class String{
public:
/*virtual*/ ~String(){}
static void operator delete(void* p) noexcept;
};
void foo(size_t extraSize){
if(void* mem = std::malloc(sizeof(String) + extraSize)){
String* p = new(mem) String;
delete p;
}
}
// The function is defined in some other *.cpp file
/*
void String::operator delete(void* p) noexcept{
std::free(p);
}
*/
https://godbolt.org/z/7aaj9o43e
Compiling with x86-64 GCC 13.2 results in:
<source>: In function 'void foo(size_t)':
<source>:14:16: warning: 'static void String::operator delete(void*)' called on pointer returned from a mismatched allocation function [-Wmismatched-new-delete]
14 | delete p;
| ^
<source>:12:31: note: returned from 'void* malloc(size_t)'
12 | if(void* mem = std::malloc(sizeof(String) + extraSize)){
| ~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~
Compiler returned: 0
Any of the following actions can remove the warning:
- Compile without optimizations (remove -O flag).
- Define 'String::operator delete(void* p)' in this translation unit (uncomment last lines).
I suppose this is GCC's bug. Am I right?