Avoid array-to-pointer decayCXX-C1000
Array-to-pointer decay refers to the automatic conversion of an array to a pointer to its first element. This means that when an array is used in an expression that expects a pointer, the name of the array is converted to a pointer to its first element.
When an array is converted to a pointer, the size information of the array is lost. This can be problematic in cases where the size of the array needs to be known, such as when iterating over the array. Stating the size in an separate
variable is not very reliable way as it might lead to access memory segments which don't belong to the array. This is common problem associated with the array-to-pointer decay.
Consider using std::span
, with C++20 or with C++14 and above you may want to consider using gsl::span
. If the array to pointer decay is intended then consider using an explicit cast to the pointer type while using the array variable as shown below.
takes_pointer(static_cast<void*>(array_var))
Bad practice
char read_next_char();
void populate(int* p, size_t n) {
for (auto i = 0; i < n; ++i) {
p[i] = read_next_char();
}
}
int main() {
int chars[16];
populate(chars, 16); // explicitly passing the length of array is bug-prone
}
Recommended
#include <span>
char read_next_char();
void populate(std::span<int> s) {
for (auto& c : s) {
c = next_character();
}
}
int main() {
int chars[16];
populate(chars); // span deduces the correct length of 16
}