Edit

Share via


Warning C26839

Array new allocation size is the result of a signed to unsigned narrowing conversion that could result in overflow if the signed value is negative.

This warning was added in Visual Studio 2022 version 17.13.

Remarks

Reports that the size specified for an array new allocation may be the result of the conversion of a possibly negative signed value to an unsigned value. For example:

int* CreateIntArray(int size)
{
    int* intArray = new int[size];
    return intArray;
}

The expression new int[size], size is signed. The compiler converts the signed value to an unsigned value to calculate how many bytes to be allocated for the array. When size is negative, the result of that calculation may overflow or have unexpected results when passed to new.

This check is the same as C26838, but applies only to new T[].

This check sometimes fails to recognize that certain checks can prevent overflows because the check is conservative.

Example

To fix the previous code example in which the size calculation might overflow due to a negative signed value, introduce a check to ensure it won't. For example:

int* CreateIntArray(int size)
{
    if (size < 0)
        return nullptr;

    int* intArray = new int[size];
    return intArray;
}

See also

C26831
C26832
C26838
C26838