16

This is dangling pointer|reference example:

#include <string>
#include <string_view>
#include <iostream>

std::string foo() {
    return "test";
}

int main() {
    std::string_view bar = foo(); // bar is pointed to destructed string
    std::cout << bar << std::endl;
}

Address sanitizer cannot catch it, at least with default options. Is it possible to catch such errors with address sanitizer?

UPD.

Reported this bug:

vladon
  • 8,158
  • 2
  • 47
  • 91

1 Answers1

3

My guess (you haven't provided compiler version) is that operator << is implemented externally so Asan can't sanitize it and detect error (unless you rebuild libstdc++ with Asan). Here's what I get with my GCC 6.2 (I slightly modified repro as I don't have access to c++1z):

  call    operator delete(void*)
.L17:
  movq    %rbx, %rsi
  movl    std::cout, %edi
  call    std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)
  call    std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)
yugr
  • 19,769
  • 3
  • 51
  • 96
  • Replace `std::cout << bar` with, for example, `std::string bar2 = bar;`. – vladon Nov 13 '17 at 14:07
  • 2
    @vladon This is very different situation. It works for me (i.e. reports `heap-use-after-free`) as long as string is longer than 16 chars. For shorter string you get SSO i.e. data is kept on stack so Asan can no longer detect heap errors. – yugr Nov 13 '17 at 14:16