Memory Sanitizer

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-27 06:08:45

问题


I am playing around with Memory Sanitizer with Clang 3.7.0 on Ubuntu 14.04. The following code does work perfectly:

#include <cstdio>

int main() {
  double ans;
  printf("Hello World: %f\n", ans);

  return 0;
}

when compiled with

 clang++ -g -O1 -fsanitize=memory -fsanitize-memory-track-origins=2 -fomit-frame-pointer sanitize.cpp -o sanitize

I was expecting an error. Doesn't Memory Sanitizer catch the fact that ans was not initialized?

Thanks for your help.


回答1:


From the clang santitizer documentation it is clear that it only deals with unitialized memory reads from dynamically allocated memory. Automatic memory is not part of sanitizer checks.




回答2:


You don't need any Sanitizer to catch this error. The compiler can figure out this error in compile time (sanitizers and valgrind work at run time). In fact, all of GCC Clang and ICC will all give a warning for this code if you switch on the warnings. This particular warning is controlled with -Wuninitialized flag. In general, it is a good practice to always use high warning level. I would recommend the following combination of warning flags, especially while learning the language:

-Wall -Wextra -pedantic

If you get some false positives, only after rigorously checking that they are really false, you can disable specific warnings. There is no reason not to use warning flags. Some projects even use -Werror flag, turning all the warnings into errors.




回答3:


Valgrind memcheck could be an option to detect the uninitialized stack values.

Valgrind documentation:

For uninitialised values originating from a heap block, Memcheck shows where the block was allocated. For uninitialised values originating from a stack allocation, Memcheck can tell you which function allocated the value, but no more than that -- typically it shows you the source location of the opening brace of the function. So you should carefully check that all of the function's local variables are initialised properly.

Reference: http://valgrind.org/docs/manual/mc-manual.html



来源:https://stackoverflow.com/questions/34141043/memory-sanitizer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!