Clang++ 6.0 Memory Sanitizer 不报告函数中未初始化的局部变量,其 return 值指示条件分支
Clang++ 6.0 Memory Sanitizer not reporting uninitialised local variable in a function whose return value dictates a conditional branch
以下代码(在 src.cpp
中)用于试验 Clang 的 Memory Sanitizer (MSan)
#include <iostream>
#include <vector>
int add(int x, int y) {
int sum;
sum = x + y;
return sum;
}
int main() {
if(add(10, 20) > 0) {
std::cout << "Greater";
}
std::cout << std::endl;
return 0;
}
我们可以清楚地看到 sum
是单元化的,会导致未定义的行为。根据 MSan Github Wiki
MemorySanitizer is bit-exact: it can track uninitialized bits in a
bitfield. It will tolerate copying of uninitialized memory, and also
simple logic and arithmetic operations with it. In general,
MemorySanitizer silently tracks the spread of uninitialized data in
memory, and reports a warning when a code branch is taken (or not
taken) depending on an uninitialized value.
这显然符合此用例,因为 if
分支将基于 sum
的初始值进行选择。但是,没有显示 error/warning 而 运行 此代码使用
编译
clang++ -fsanitize=memory -fsanitize-memory-track-origins -O0 -std=c++14 src.cpp -o src
Clang 6.0 用于 Linux x86_64。
sum并不是未初始化,因为接下来的指令就是sum变量的赋值。
此代码与:
int sum = x + y;
这就是它被初始化的原因。
以下代码(在 src.cpp
中)用于试验 Clang 的 Memory Sanitizer (MSan)
#include <iostream>
#include <vector>
int add(int x, int y) {
int sum;
sum = x + y;
return sum;
}
int main() {
if(add(10, 20) > 0) {
std::cout << "Greater";
}
std::cout << std::endl;
return 0;
}
我们可以清楚地看到 sum
是单元化的,会导致未定义的行为。根据 MSan Github Wiki
MemorySanitizer is bit-exact: it can track uninitialized bits in a bitfield. It will tolerate copying of uninitialized memory, and also simple logic and arithmetic operations with it. In general, MemorySanitizer silently tracks the spread of uninitialized data in memory, and reports a warning when a code branch is taken (or not taken) depending on an uninitialized value.
这显然符合此用例,因为 if
分支将基于 sum
的初始值进行选择。但是,没有显示 error/warning 而 运行 此代码使用
clang++ -fsanitize=memory -fsanitize-memory-track-origins -O0 -std=c++14 src.cpp -o src
Clang 6.0 用于 Linux x86_64。
sum并不是未初始化,因为接下来的指令就是sum变量的赋值。 此代码与:
int sum = x + y;
这就是它被初始化的原因。