c++arrayspointersargumentssecure-coding

How can you enable compiler warning on array argument decaying to pointer


I learned that in C++, array arguments decay to pointer arguments. As a result,

void PrintArray(int arr[4])
{
    std::cout << arr[0] << std::endl;
    std::cout << arr[1] << std::endl;
    std::cout << arr[2] << std::endl;
    std::cout << arr[3] << std::endl;
}

decays to void PrintArray(int arr*) { ... }

If the declaration was written in the pointer form, my amateur interns would not assume there were 4 members in the array.

I figure the array form syntax on arguments is historical. With C++20 and modern compilers, are there compiler warnings or options to disallow this form? We primarily use Microsoft Visual C++.

If so, I will ask my coworkers to compile code with this option, so they will not make stupid mistakes!

I am seeking a solution on Static Analysis or something I can deploy on Continuous Integration.


Solution

  • I don't think there is a compiler warning for that situation.

    The good news is that the problem is well identified in the MISRA C++ rule "An array passed as a function argument shall not decay to a pointer" (MISRA-2008-5.2.12, MISRA-2023-7.11.2). This rule does not forbid array parameters as you are looking for, but it will flag calls to the function with smaller arrays or with pointers, that might lead to out of bounds situations.

    The other good news is that static analysis tools support MISRA rules, and the one that interests us here (example: PVS or SonarQube)