Search code examples
c++address-sanitizer

stack use after scope: a valid report, or a false positive?


I have found a stack-use-after-scope error in our code-base (g++ -fsanitize=address), and would like to know if that's a valid concern, and I should go and fix every occurrence of such pattern, or is it a false positive from address sanitizer?

Minimal and simplified example is as follows:

#include <string>
#include <stdio.h>

struct MyStr
{
    MyStr() = default;
    MyStr(const char *s) : text(s) {};
    MyStr substr(size_t length) const
    {
        auto begin = text.begin();
        auto end = begin + length;
        return MyStr(std::string(begin, end));
    }
    const char *c_str()
    {
        return text.c_str();
    }
    private:
    explicit MyStr(std::string s): text(std::move(s)){};
    std::string text;


};
struct Other
{
    std::string text;
    Other(const std::string &s): text(s){};
};

void usage(const char *s)
{
    Other other(s); // BAM!!!
}
int main() {
    MyStr str("use-after-scope-example");
    auto cs = str.substr(2).c_str();
    usage(cs);
    return 0;
}

This is C++11 if that's of any importance, and compiler is g++ (SUSE Linux) 11.1.1 20210617 [revision 79c1185de4]


Solution

  • Yes, the error is correctly reported (Although BAM!!! seems to be misplaced). This line:

    auto cs = str.substr(2).c_str();
    

    declares cs as pointer to character buffer, which is removed once the temporary returned by str.substr(2) is destroyed (which happens in the end of the expression).