Array element count computed with sizeof division
ID |
c.maintainability.manual_array_size |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Modern Alternative |
Language |
C / C++ |
Description
This computes the element count with sizeof(array) / sizeof(array[0]). The idiom silently returns a meaningless number if array decays to a pointer — a parameter, a member reached through this, or a variable refactored from an array into a pointer — since it then divides the pointer’s size by its pointee’s size instead of failing to compile. std::size(array) is equivalent for a real array and does not compile at all on a pointer.
Rationale
This computes the element count with sizeof(array) / sizeof(array[0]). The idiom silently returns a meaningless number if array decays to a pointer — a parameter, a member reached through this, or a variable refactored from an array into a pointer — since it then divides the pointer’s size by its pointee’s size instead of failing to compile. std::size(array) is equivalent for a real array and does not compile at all on a pointer.
The following code illustrates the pattern detected by this rule:
int global_arr[10];
void f()
{
int local[5];
// FLAGGED: Array element count computed with sizeof division
size_t n = sizeof(global_arr) / sizeof(global_arr[0]);
// FLAGGED: Array element count computed with sizeof division
size_t m = sizeof(local) / sizeof(local[0]);
size_t k = sizeof(global_arr) / sizeof(int);
size_t bad = sizeof(global_arr) / 4;
size_t v = std::size(global_arr);
}