stella
stella

Reputation: 2596

Understanding new operators

What happened if we invoke different forms of the operator new and operator delete?

class A
{
public:
    void* operator new  ( std::size_t count, const char* msg );
};

void* A::operator new  ( std::size_t sz, const char* msg ){
    std::printf("global op new called, message = %s",msg);
    return std::malloc(sz);
}

int main(){
    A *a = new ("message") A;
    delete a;
}

Does the program have UB in that case? What is Standard talking about that?

Upvotes: 0

Views: 70

Answers (1)

Peter
Peter

Reputation: 36637

Yes, your code has undefined behaviour, in a number of ways.

In general terms, the result is undefined unless the form of release matches the form of allocation. That includes a mismatch of form of operator new. (Placement new is a bit special and different, but I won't go there).

Also, the OP's comments below the original post are 100% incorrect. There is no requirement that any form of operator new or operator delete use malloc() and free() (or related functions). Accordingly, the statement delete a has undefined behaviour, since it means that memory allocated using malloc() is released using the global operator delete().

Upvotes: 3

Related Questions