Rediger

Del via


Warning C26831

Allocation size might be the result of a numerical overflow

Remarks

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

void *SmallAlloc(int);

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

If i+j overflows, SmallAlloc returns a buffer that is smaller 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.

The 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(int i, int j)
{
    if (i < 0 || j < 0 )
    {
        return;
    }

    if (i > 100 || j > 100)
    {
        return;
    }

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

See also

C26832
C26833