void test(int *arr) {
int arr_len = sizeof(arr) / sizeof(*arr); // warn, incorrect way to compute number of array elements
}
Enabled under -Wall (same behaviour as GCC)
Differential D52949
[Diagnostics] Implement -Wsizeof-pointer-div xbolva00 on Oct 5 2018, 2:41 PM. Authored by
Details void test(int *arr) { int arr_len = sizeof(arr) / sizeof(*arr); // warn, incorrect way to compute number of array elements } Enabled under -Wall (same behaviour as GCC)
Diff Detail Event Timeline
Comment Actions It looks like you ran clang-format on all of lib/Sema/SemaExpr.cpp and changed many lines that are irrelevant to your patch. Can you undo that, please? Comment Actions Can you add tests with arrays? Comment Actions Yes :)
What do you suggest? "division produces the incorrect number of array elements; pass the length of array as a function argument"?
Ok, good idea. Comment Actions Second thought, I don't think we should recommend std::size here (maybe it should be okay for clang static analyzers) uint32_t data[] = {10, 20, 30, 40}; Comment Actions IMHO, a clang-tidy checker is more suitable than clang static analyzer to indicate to the developers that we should prefer std::size to sizeof(data)/sizeof(*data). What I want to know most is whether we should emit a warning for the code below. I haven't been able to test the patch yet, but intuitively, this patch will emit a warning. int foo(int *p) { int d = sizeof(p) / sizeof(char); // Should we emit a warning here? return d; } GCC keep silent about this case, and I agree with it, see https://gcc.godbolt.org/z/ZToFqq. What do you think about this case? Comment Actions Any ideas for better warning message? Except for the warning text, I see this patch as ready. Comment Actions Sorry for the long delay for this patch! The implementation is fine for me. However, I'm the newbie on clang diagnostics and have no further insight into this checker. @aaron.ballman may have more valuable insights into this checker.
Comment Actions
We match the GCC behaviour here, except the case: But I think it is ok now.
Comment Actions LGTM with a minor formatting nit.
|
Do you really need the explicit diagnostic group? Given that there's only one diagnostic here, I would lower this into the diag (see below).