Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cpp: new experimental query cpp/guarded-free #16331

Merged
merged 4 commits into from May 1, 2024

Conversation

mario-campos
Copy link
Contributor

This PR introduces a new experimental query that finds instances of free() guarded by a superfluous NULL check.

Copy link
Contributor

QHelp previews:

cpp/ql/src/experimental/Best Practices/GuardedFree.qhelp

Guarded Free

The free function, which deallocates heap memory, may accept a NULL pointer and take no action. Therefore, it is unnecessary to check its argument for the value of NULL before a function call to free. As such, these guards may hinder performance and readability.

Recommendation

A function call to free should not depend upon the value of its argument. Delete the if condition preceeding a function call to free when its only purpose is to check the value of the pointer to be freed.

Example

void test()
{
    char *foo = malloc(100);

    // BAD
    if (foo)          
        free(foo);

    // GOOD
    free(foo);
}

References

Copy link
Contributor

@MathiasVP MathiasVP left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@MathiasVP MathiasVP merged commit a8f2cbc into github:main May 1, 2024
15 checks passed
@mario-campos mario-campos deleted the mario-campos/guarded-free branch May 1, 2024 16:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants