Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Sanitizer

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.

like image 772
InsideLoop Avatar asked Dec 07 '15 18:12

InsideLoop


People also ask

What is memory sanitizer?

Memory Sanitizer (MSan) is a fast detector used for uninitialized memory in C/C++ programs. It uses a compile-time instrumentation to ensure that all memory access at runtime uses only memory that has been initialized.

How does the AddressSanitizer work?

AddressSanitizer dedicates one-eighth of the virtual address space to its shadow memory and uses a direct mapping with a scale and offset to translate an applica- tion address to its corresponding shadow address.

What is an AddressSanitizer error?

AddressSanitizer (aka ASan) is a memory error detector for C/C++. It finds: Use after free (dangling pointer dereference) Heap buffer overflow.

What are C++ sanitizers?

The C/C++ compilers Clang/LLVM and GCC support so-called sanitizers. These sanitizers are built into the application code and track the execution at runtime to report execution errors. There are currently four interesting sanitizers: AddressSanitizer and LeakSanitizer. ThreadSanitizer.


2 Answers

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.

like image 197
SergeyA Avatar answered Sep 21 '22 01:09

SergeyA


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.

like image 21
Ilya Popov Avatar answered Sep 22 '22 01:09

Ilya Popov