Main Content

MISRA C++:2023 Rule 18.5.2

Program-terminating functions should not be used

Since R2024b

Description

Rule Definition

Program-terminating functions should not be used.

Rationale

Standard library functions such as std::abort(), std::exit(), std::quick_exit(), std::terminate(), and std::_Exit() terminate the program immediately. When the program terminates due to calls to these functions, it is implementation-dependent whether the compiler releases the allocated resources and unwinds the stack.

Not releasing allocated resources or failing to unwind the stack can lead to issues such as memory leaks or permanently locked files. Avoid calling these program-terminating functions.

Polyspace Implementation

The rule checker reports a violation if you explicitly call one of these functions in your code:

  • Unsafe termination functions such as std::_Exit(), std::abort(), and std::quick_exit()

  • The function std::terminate()

  • The function std::exit()

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

In this example, unsafe termination functions terminate the program. These functions do not perform the essential cleanup operations such as calling destructors. For instance, the destructors of the staticObject or the three instances of localObject are not invoked. Any resource allocated by these objects is leaked. Polyspace reports violations on the use of such unsafe termination functions.

#include<cstdlib>
class obj
{
public:
	obj() noexcept(false){}
	obj(const obj& a){/*...*/}
	~obj(){/*...*/}
};
static obj staticObject;
void foo(){
	obj localObject;
	//...
	std::_Exit(-1);  //Noncompliant
}
void bar(){
	obj localObject;
	//...
	std::abort();  //Noncompliant
}
void foobar(){
	obj localObject;
	//...
	std::quick_exit(-1);  //Noncompliant
}

Invoking std::terminate() explicitly results in abrupt termination of the program without calling the destructors of the local and static objects. Polyspace reports a violation of this rule.

#include<cstdlib>
#include<exception>
class obj
{
public:
	obj() noexcept(false){}
	obj(const obj& a){/*...*/}
	~obj(){/*...*/}
};
static obj staticObject;

void foobar(){
	obj localObject;
	//...
	std::terminate();   //Noncompliant
}

Check Information

Group: Exception Handling
Category: Advisory

Version History

Introduced in R2024b