我希望这个问题不会超出 SO 的范围;如果是(在那种情况下很抱歉),请告诉我它属于哪里,我会尝试将它移到那里。
在 C/C++ 中用于静态代码分析的SAL 注释的概念对我来说似乎非常有用。以 MSDN 上错误实现的wmemcpy
示例为例:Understanding SAL:
wchar_t * wmemcpy(
_Out_writes_all_(count) wchar_t *dest,
_In_reads_(count) const wchar_t *src,
size_t count)
{
size_t i;
for (i = 0; i <= count; i++) { // BUG: off-by-one error
dest[i] = src[i];
}
return dest;
}
MSDN 说“代码分析工具可以通过单独分析这个函数来捕获错误”,这看起来很棒,但问题是当我将此代码粘贴到 VS 2017 社区时,代码分析中不会弹出关于此的警告,即使使用启用所有分析警告。(其他类似的警告C26481 Don't use pointer arithmetic. Use span instead (bounds.1).
。)
另一个应该产生警告的例子(至少根据对What is the purpose of SAL(Source Annotation Language)以及 SAL 1 和 2 有什么区别? )的回答,但没有:
_Success_(return) bool GetASmallInt(_Out_range_(0, 10) int& an_int);
//main:
int result;
const auto ret = GetASmallInt(result);
std::cout << result;
还有一个不正确警告的情况:
struct MyStruct { int *a; };
void RetrieveMyStruct(_Out_ MyStruct *result) {
result->a = new int(42);
}
//main:
MyStruct s;
RetrieveMyStruct(&s);
// C26486 Don't pass a pointer that may be invalid to a function. Parameter 1 's.a' in call to 'RetrieveMyStruct' may be invalid (lifetime.1).
// Don't pass a pointer that may be invalid to a function. The parameter in a call may be invalid (lifetime.1).
result
显然标有_Out_
and not_In_
或_Inout_
因此此警告在这种情况下没有意义。
我的问题是:为什么 Visual Studio 的基于 SAL 的代码分析看起来很糟糕;我错过了什么吗?Visual Studio Professional 或 Enterprise 在这方面可能更好吗?或者有没有可以更好地做到这一点的工具?
如果它真的很糟糕:这是一个已知问题吗?是否有计划改进这种类型的分析?