Rediger

Del via


Warning C26832

Allocation size is the result of a narrowing conversion that could result in overflow

Remarks

This warning reports that the size specified for an allocation may be the result of a narrowing conversion that results in a numerical overflow. For example:

void* SmallAlloc(int);

void foo(unsigned short i, unsigned short j)
{
    unsigned short size = i + j;
    
    int* p = (int*)SmallAlloc(size); // Warning: C26832
    p[i] = 5;
}

In the expression i + j, both i and j are promoted to integers, and the result of the addition is stored in a temporary integer. Then, the temporary integer is implicitly cast to an unsigned short before the value is stored in size. The cast to unsigned short might overflow, in which case SmallAlloc may return a smaller buffer than expected. That will likely lead to out of bounds attempts to access the buffer later on. This code pattern can result in remote code execution vulnerabilities

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.

This warning is available in Visual Studio 2022 version 17.7 and later versions.

Example

To fix the previous code example in which i+j might overflow, introduce a check to make sure it won't. For example:

void *SmallAlloc(int);

void foo(unsigned short i, unsigned short j)
{
    if (i > 100 || j > 100)
        return;

    unsigned short size = i + j;
    
    int* p = (int*)SmallAlloc(size);
    p[i] = 5;
}

See also

C26831
C26833