std::mutex allocated with new

ID

c.correctness.dynamically_allocated_mutex

Severity

low

Remediation Complexity

medium

Remediation Risk

medium

Remediation Effort

low

Resource

Concurrency

Language

C / C++

Description

This mutex is heap-allocated with new instead of owning a scope on the stack. A mutex’s job is to guard access for as long as some other resource is alive, and that lifetime is easiest to get right when the compiler manages it — a heap mutex adds a lifetime the code must track by hand and can leak, be freed while still locked, or outlive the resource it was meant to protect. Give it automatic storage duration, or bundle it with the resource it guards in the same object.

Rationale

This mutex is heap-allocated with new instead of owning a scope on the stack. A mutex’s job is to guard access for as long as some other resource is alive, and that lifetime is easiest to get right when the compiler manages it — a heap mutex adds a lifetime the code must track by hand and can leak, be freed while still locked, or outlive the resource it was meant to protect. Give it automatic storage duration, or bundle it with the resource it guards in the same object.

The following code illustrates the pattern detected by this rule:

void heap_default()
{
    // FLAGGED: std::mutex allocated with new
    std::mutex *lock = new std::mutex;
    delete lock;
}

Remediation

Follow secure coding practices and review the references below for detailed remediation guidance.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved