Guarded Free¶
ID: cpp/guarded-freeKind: problemSecurity severity: Severity: recommendationPrecision: very-highTags: - maintainability - readabilityQuery suites: - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
Thefree function, which deallocates heap memory, may accept a NULL pointer and take no action. Therefore, it is unnecessary to check the argument for the value of NULL before a function call tofree. As such, these guards may hinder performance and readability.
Recommendation¶
A function call tofree should not depend upon the value of its argument. Delete the condition preceding a function call tofree when its only purpose is to check the value of the pointer to be freed.
Example¶
voidtest(){char*foo=malloc(100);// BADif(foo)free(foo);// GOODfree(foo);}
In this example, the condition checking the value offoo can be deleted.
References¶
The Open Group Base Specifications Issue 7, 2018 Edition:free - free allocated memory.