Main Content

CERT C: Rec. WIN01-C

Do not forcibly terminate execution

Since R2026a

Description

Do not forcibly terminate execution1

Polyspace Implementation

The rule checker checks for the issue Use of TerminateThread() and TerminateProcess() functions to terminate threads.

Examples

expand all

Issue

This issue occurs if you force the termination of a thread using one of the functions TerminateThread() or TerminateProcess(). The rule checker flags the issue only if you use the version of these functions declared in Windows.h, which comes as part of the Windows® Software Development Kit (SDK).

Risk

If a thread terminates normally, thread-specific resources are released automatically by the system and other parts of the application are notified of the thread termination. If you force the termination of a thread, these cleanup activities do not run, resulting in resource leaks.

Fix

If a condition occurs that requires the termination of a thread, request the thread to terminate itself gracefully. You can trigger the graceful termination of a thread by returning an exit code from the thread entry point function and then waiting for the thread to be terminated.

Example — Use of TerminateThread() to Terminate Thread

In this example, the TerminateThread() function is used to forcibly terminate the thread controlled by the thread handle hThread if the thread is still active after a termination condition is set.


          
          #include <Windows.h>

// Shared variable to trigger termination
volatile LONG terminateCondition = 0;

// Thread function that simulates some work
DWORD WINAPI ThreadProc(LPVOID lpParam) {
    while (1) {
        // Thread is running
        // Check if the condition to terminate the thread is met
        if (InterlockedCompareExchange(&terminateCondition, 0, 1) == 1) {
            // Thread exiting gracefully
            return 0;
        }
    }
}

int main() {
    HANDLE hThread;
    DWORD dwThreadId;

    // Create a new thread
    hThread = CreateThread(
        NULL,                   // Default security attributes
        0,                      // Default stack size
        ThreadProc,             // Thread function
        NULL,                   // Parameter to thread function
        0,                      // Default creation flags
        &dwThreadId);           // Returns the thread identifier

    if (hThread == NULL) {
        // Thread creation failed
        return 1;
    }

    // Let the thread run for a few seconds
    Sleep(5000);

    // Set the condition to terminate the thread
    InterlockedExchange(&terminateCondition, 1);

    // Wait a moment to see if the thread exits gracefully
    Sleep(2000);

    DWORD exitCode;
    if (GetExitCodeThread(hThread, &exitCode) && exitCode == STILL_ACTIVE) {
        // If the thread is still active, forcibly terminate it
        if (TerminateThread(hThread, 0)) { //Noncompliant
            // Thread forcibly terminated
        } else {
            // Failed to terminate thread
        }
    }

    // Close the thread handle
    CloseHandle(hThread);

    return 0;
}
Correction – Wait for Thread to Exit Gracefully

Since the code already uses InterlockedExchange() and InterlockedCompareExchange() functions to gracefully exit the thread when a termination condition is set, one possible correction is to wait for the thread to complete exiting using the WaitForSingleObject() function with INFINITE duration.


          
          #include <Windows.h>

// Shared variable to signal the thread to exit
volatile LONG terminateCondition = 0;

// Thread function that simulates some work
DWORD WINAPI ThreadProc(LPVOID lpParam) {
    while (1) {
        // Thread is running
        // Check if the condition to terminate the thread is met
        if (InterlockedCompareExchange(&terminateCondition, 0, 1) == 1) {
            // Thread exiting gracefully
            return 0;
        }
    }
    return 0;
}

int main() {
    HANDLE hThread;
    DWORD dwThreadId;

    // Create a new thread
    hThread = CreateThread(
        NULL,                   // Default security attributes
        0,                      // Default stack size
        ThreadProc,             // Thread function
        NULL,                   // Parameter to thread function
        0,                      // Default creation flags
        &dwThreadId);           // Returns the thread identifier

    if (hThread == NULL) {
        // Thread creation failed
        return 1;
    }

    // Let the thread run for a few seconds
    Sleep(5000);

    // Set the condition to terminate the thread
    InterlockedExchange(&terminateCondition, 1);

    // Wait for the thread to exit gracefully
    WaitForSingleObject(hThread, INFINITE);

    // Thread exited gracefully

    // Close the thread handle
    CloseHandle(hThread);
}

Check Information

Group: Rec. 51. Microsoft Windows (WIN)
PQL Name: std.cert.WIN01_C

Version History

Introduced in R2026a


1 This software has been created by MathWorks incorporating portions of: the “SEI CERT-C Website,” © 2017 Carnegie Mellon University, the SEI CERT-C++ Web site © 2017 Carnegie Mellon University, ”SEI CERT C Coding Standard – Rules for Developing safe, Reliable and Secure systems – 2016 Edition,” © 2016 Carnegie Mellon University, and “SEI CERT C++ Coding Standard – Rules for Developing safe, Reliable and Secure systems in C++ – 2016 Edition” © 2016 Carnegie Mellon University, with special permission from its Software Engineering Institute.

ANY MATERIAL OF CARNEGIE MELLON UNIVERSITY AND/OR ITS SOFTWARE ENGINEERING INSTITUTE CONTAINED HEREIN IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT.

This software and associated documentation has not been reviewed nor is it endorsed by Carnegie Mellon University or its Software Engineering Institute.