Main Content

Throw argument expression calls new

The argument expression in a throw statement allocates memory by calling new, which can result in abrupt termination of the program and resource leaks

Since R2023b

Description

This defect occurs when the argument expression of a throw statement allocates memory by calling new. For instance, consider this code:

try{
	//...
	throw new std::string{"Error"};
}catch(...){
	//...
}
The throw expression calls new to allocate memory before raising the exception. Polyspace® reports a defect.

Risk

  • A failed call to new can result in an exception, such as std::bad_alloc. Such an exception in the throw expression becomes an unhandled exception, resulting in abrupt program termination and resource leaks. See Argument expression of throw statement might raise unexpected exception.

  • If you call new when raising an exception, it is not clear where you can safely deallocate the memory. The allocated memory might be leaked.

Fix

To fix this issue, remove the call to new. For instance, instead of this code:

throw new T;
Use this code:
throw T;

Examples

expand all

In this example, the throw statement in the function foo calls new. There are two possible outcome:

  • The call to new fails and results in an exception. This exception becomes an unhandled exception, resulting in an abrupt termination of the program.

  • The call to new succeeds and a new memory is allocated for an std::exception object. To prevent a memory leak, the catch block must perform a delete operation.

The call to new in a throw statement might result in program termination or a memory leak. Polyspace reports a defect.

#include <exception>

void foo()
{
    try
    {
        throw new std::exception(); 

    } catch (std::exception *t)
    {
        delete t; // requires cleanup
    }
}
Correction — Omit new

To resolve this defect, omit the call to new in the throw statement.

#include <exception>

void foo()
{
    try
    {
        throw std::exception();

    } catch (const std::exception& t)
    {
        // no cleanup required
    }
}

Result Information

Group: C++ Exception
Language: C++
Default: Off
Command-Line Syntax: THROW_EXPRESSION_CALLS_NEW
Impact: Medium

Version History

Introduced in R2023b