Skip to content

Latest commit

 

History

History
58 lines (40 loc) · 2 KB

c26832.md

File metadata and controls

58 lines (40 loc) · 2 KB
title description ms.date f1_keywords helpviewer_keywords
Warning C26832
Describes the Microsoft C/C++ code analysis warning C26832, its causes, and how to address it.
03/20/2023
C26832
ALLOCATION_POTENTIAL_OVERFLOW_AFTER_CAST
C26832

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