Edit

Share via


Warning C26838

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 allocation may be the result of the conversion of a possibly negative signed value to an unsigned value. For example:

void* CustomAlloc(size_t);

int* CreateIntArray(int numberOfElements)
{
    int* p = (int*)CustomAlloc(numberOfElements * sizeof(int)); // Warning: C26838

    return p;
}

The expression numberOfElements * sizeof(int), numberOfElements is signed and sizeof(int) is unsigned. On 64-bit machines, numberOfElements is promoted to an unsigned value when multiplied by sizeof(int). When numberOfElements is negative, the resulting value may overflow or have unexpected results when passed to CustomAlloc.

This check applies to common allocation functions like new, malloc, and VirtualAlloc. The check also applies to custom allocator functions that have alloc (case insensitive) in the function name.

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 numberOfElements * sizeof(int) might overflow due to a negative signed value, introduce a check to ensure it won't. For example:

void* CustomAlloc(size_t);

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

    int* p = (int*)CustomAlloc(numberOfElements * sizeof(int));
    // ...
    return p;
}

In the previous example, checking for a negative value addresses the C26832 warning. Depending on the size of the types involved, this check may result in a different warning such as C26831. For example, on a 32-bit system, both int and size_t are 32 bits, so the result of the multiplication can still overflow without negative values.

See also

C26831
C26832
C26833
C26833