Static Analysis Problem Type Reference
The C++ "new" operator was overridden using a non-standard form.
The standard C++ new operator takes one argument of type size_t and throws an exception of type "std::bad_alloc" when all available memory is exhausted. The standard C++ library provides two variants of this behavior that use the so-called "placement new" syntax. The "placement new" syntax provides an additional parameter that modifies the behavior of the "new" invocation. The value of this parameter is placed after the word "new."
This diagnostic flags programs that attempt to override the "new" operator with a non-standard form. Generally, this indicates a mistaken approach to defining your own custom allocator, although there are cases where you might legitimately want to do this for debugging purposes.
If you simply wish to avoid exceptions (and instead return null when out of memory), you must include the standard C++ library header <new> in your source code. This declares the global object std::nothrow, which may be passed as the second parameter in the placement new syntax, as in "p = new (std::nothrow) T;"
If you would like to define your own custom allocator, you can declare your own operator new as a class member function, using the "placement new" syntax. In this case, the additional "new" parameter is usually an instance of a storage allocator class, and the implementation of the "new" member function is to return storage obtained from this allocator.
Destroying an object that was allocated in this way requires some care. There is no placement delete expression, so you cannot use it to invoke the custom deallocator. You must either write a destruction function that invokes the custom deallocator after calling the destructor, or simply call the destructor and the placement delete function directly. Do not use the delete operator to tear down an object like this because this would cause the wrong operator delete function to be called.
|
ID |
Code Location |
Description |
|---|---|---|
|
1 |
Definition |
The place where the non-standard "new" function was declared |
#include <stdio.h>
#include <stdlib.h>
#include <new>
#define DEBUG_NEW // to demonstrate the error
#if defined(DEBUG_NEW)
void * operator new (size_t size, const char* file, int line);
void * operator new[] (size_t size, const char* file, int line);
#define New new(__FILE__, __LINE__)
#else
#define New new
#endif
// legitimate but non-standard redefinition of new operator
void * operator new (size_t size, const char* file, int line)
{
if (void * p = ::operator new (size, std::nothrow))
return p ;
printf("allocation failed on line %d in file %s\n",
line, file);
exit(-1);
}
int main(int argc, char **argv)
{
int * p = New int;
*p = 1;
delete p;
}