Page MenuHomePhabricator

[clang-tidy] Extend bugprone-sizeof-expression check to detect sizeof misuse in pointer arithmetic
ClosedPublic

Authored by baloghadamsoftware on May 2 2019, 1:30 AM.

Details

Summary

Some programmers tend to forget that subtracting two pointers results in the difference between them in number of elements of the pointee type instead of bytes. This leads to codes such as size_t size = (p - q) / sizeof(int) where p and q are of type int*. Or similarily, if (p - q < buffer_size * sizeof(int)) { ... }. This patch extends bugprone-sizeof-expression to detect such cases.

Diff Detail

Event Timeline

Herald added a project: Restricted Project. · View Herald TranscriptMay 2 2019, 1:30 AM

Type int in tests replaced by struct S because it has more "sugar". Check also fixed to handle this case.

Out of curiosity, have you run this over any large code bases to see what the false positive and true positive rate is?

clang-tidy/bugprone/SizeofExpressionCheck.cpp
217

Missing full stop at the end of the comment.

Dot added to the end of the comment.

Out of curiosity, have you run this over any large code bases to see what the false positive and true positive rate is?

Neither false, nor true positives found so far. I ran it on several open-source projects.

aaron.ballman accepted this revision.May 3 2019, 5:52 AM

Out of curiosity, have you run this over any large code bases to see what the false positive and true positive rate is?

Neither false, nor true positives found so far. I ran it on several open-source projects.

Hmm, I am a little bit skeptical about the utility of this compared to the expense of making the check marginally slower. However, I don't have any specific objections and so I'm not opposed to the patch. LG!

This revision is now accepted and ready to land.May 3 2019, 5:52 AM

Hmm, I am a little bit skeptical about the utility of this compared to the expense of making the check marginally slower. However, I don't have any specific objections and so I'm not opposed to the patch. LG!

I think that the open-source projects I used for testing are mature enough for such amateur errors. However many beginner programmers make such errors.

This revision was automatically updated to reflect the committed changes.