Skip to content

[FR] clang-tidy check for nullptr check when calling delete or free #118527

@FalcoGer

Description

@FalcoGer

Plenty of people do not know that calling free, std::free or delete on a nullptr is a no-op.
If a check for nullptr is applied to only such a call, it should be flagged and a fix proposed to remove it.

Possible name could be "readability-redundant-nullptr-check" or it could be in "misc-".

int* ptr{nullptr}
if (!ptr)  // check not required
{
    delete ptr;
}

// fixes to
delete ptr;

All standard checks should be supported !ptr, ptr != nullptr, ptr != NULL, etc
Both extra scopes and single line if checks should be supported.

int* ptr{nullptr}
if (!ptr)  // check not required
    delete ptr; // no scope

if (!ptr)  // check not required
{{{{
    delete ptr; // lots of scopes
}}}}

Assignment of nullptr after the delete should also trigger this.
Fix should of course retain the assignment.

int* ptr{nullptr}
if (!ptr)  // check not required
{
    delete ptr;
    ptr = nullptr; // extra assignment of nullptr. should also check for 0, NULL.
}


// fixes to
delete ptr;
ptr = nullptr;

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions