Search code examples
c++freesanitizer

free invalid pointer disappeared after applying address sanitizer


I got a free: invalid pointer when running my project. But when I try to hunt the root cause using -fsanitize=address, the error disappears. When I remove the sanitizer, the error appears again. Can anyone give some hint about what was happening and how to pinpoint the problem in such a case? Thanks!

Update:

I understand it is hard to give suggestions without code. As the project is pretty big and I am still trying to build a minimal working example, I cannot provide any code right now. So I would like to change my question to a more general one:

According to my understanding of address sanitizer, it should track all allocation/access operations and report error if there is any invalid access. So if there is an error when not applying address sanitizer, the error should be still there after applying sanitizer. Is this understanding correct?


Solution

  • Since you asked a vague and inspecific question, I'll provide a cliche and inspecific answer...

    Try not to allocate and de-allocate directly, yourself

    Read this SO question and its answers:

    Why should C++ programmers minimize use of 'new'?

    if you use containers (std::vector, std::array etc.), or smart pointers (std::unique_ptr, std::shared_ptr) - then allocation and de-allocation will be taken care of for you. You won't double-deallocate those resources. It is actually quite feasible to avoid new and delete altogether in many applications.

    Dot your i's and cross your t's - with compiler warnings

    Many issues are actually detected by the compiler, but are not technically invalid C++, so it lets them pass and only gives you a warning.

    Make the effort to address all of your compiler warnings, and - compile with more warnings enabled. For example, with g++, use at least -W -Wall -Wextra, and there are more still.

    An out-of-bounds write?

    You may be writing out-of-bounds, or through a stale pointer, by mistake. That could possibly cause the pointer you're trying to free to get overwritten. To try to detect this, running your program with valgrind may be useful. See:

    How does valgrind work?

    an alternative is using another kind of sanitizer - a memory santizer (Msan). Read about the difference between those and valgrind to decide which would work for you:

    Memory/Address Sanitizer vs Valgrind