Skip to content

Commit 7e071c1

Browse files
committed
Learn Editor: Update c26839.md
1 parent 869becf commit 7e071c1

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

docs/code-quality/c26839.md

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,50 @@ ms.service: # Add the ms.service or ms.prod value
1212
ms.topic: # Add the ms.topic value
1313
ms.date: 08/22/2024
1414
---
15-
Warning C26839
15+
# Warning C26839
16+
17+
18+
> 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
19+
20+
## Remarks
21+
22+
This warning reports that the size specified for a array new allocation may be the result of the conversion of a possibly negative signed value to an unsigned value. For example:
23+
24+
```cpp
25+
int* CreateIntArray(int size)
26+
{
27+
int* intArray = new int[size];
28+
return intArray;
29+
}
30+
```
31+
32+
In the expression `new int[size]`, `size` is signed. The compiler will convert the signed value to an unsigned value when calculating how many bytes need to be allocated for the array.
33+
When `size` is negative, the result of that calculation may overflow or have unexpected results.
34+
35+
This check is the same as [`C26838`](c26838.md), but applies only to array new `new T[]`.
36+
37+
This check sometimes fails to recognize that certain checks can prevent overflows because the check is conservative.
38+
39+
This warning is available in Visual Studio 2022 version 17.12 and later versions.
40+
41+
## Example
42+
43+
To fix the previous code example in which the size calculation might overflow due to a negative signed value, introduce a check to make sure it won't. For example:
44+
45+
```cpp
46+
int* CreateIntArray(int size)
47+
{
48+
if (size < 0)
49+
return nullptr;
50+
51+
int* intArray = new int[size];
52+
return intArray;
53+
}
54+
```
55+
56+
## See also
57+
58+
[`C26831`](c26831.md)\
59+
[`C26832`](c26832.md)\
60+
[`C26838`](c26833.md)\
61+
[`C26838`](c26838.md)

0 commit comments

Comments
 (0)