It is not a problem with your code but a false positive from the analyser.
If you open the + next to the message in the Error List (assuming you include Intellisense errors in it), the analyser will show the step it used to make the deduction.
You could tell the analyser that mem is greater than size using _Analysis_assume_(mem >= size);
. There are other options to help the analyser make correct guess.
However, if you work on a large project and you get that kind of error after an update of Visual Studio that add a new analysis and have a lot of false positive, you might prefer to disable some analysis rules if you don't have known memory problems with your application.
See https://docs.microsoft.com/en-us/cpp/code-quality/how-to-specify-additional-code-information-by-using-analysis-assume?view=msvc-160 for more information.
Alternatively, just after increasing mem
you can add the following condition for the rest of the function:
if (mem > size) { ... }
Or even add an assertion:
assert(mem > size);
It look like the analyser is not real time so adjusting the code might not immediatly remove the warning. Analysing the file using the Analyser menu of Visual Studio should works immediatly (if the analyser is enabled as it seems that old analysis result can survive compilation and even rebuilding etc...).
An untested alternative would be to have a allocate_if_full
function instead. As all required information would be in the same function, analyser might not be fooled.
Using standard algorithm
Also, if you use std::copy
instead of hand-coded loop, that the analyser won't report a potential problem.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…