Search code examples
c++c++11shared-ptr

Strange behaviour of std::make_shared


I have a very strange behaviour I can't understand.

This test passes:

CipString str = *std::make_shared<CipString>("Bye!").get();
EXPECT_EQ(static_cast<std::string>(str), "Bye!"); 

But this not:

CipString *str = std::make_shared<CipString>("Bye!").get();
EXPECT_EQ(static_cast<std::string>(*str), "Bye!");

I got an error:

Expected: static_cast(*str)

Which is: "p\x15\x97\x1"

To be equal to: "Bye!"

The CipString's code:

class CipString{
  public:

  CipString(const std::string& str) {
    length = str.size();
    string.reset(new uint8_t[length]);
    std::copy(str.begin(), str.end(), string.get());
  }

  operator std::string() const {
    std::string str("", length);
    std::copy(string.get(), string.get() + length, str.begin());
    return str;
  }

  uint16_t length; /**< Length of the String (16 bit value) */
  std::shared_ptr<uint8_t> string; /**< Pointer to the string data */
};

Solution

  • This line:

    CipString *str = std::make_shared<CipString>("Bye!").get();
    

    creates a shared_ptr that is destroyed just after the ;. str is a dangling pointer after that, and your test invokes undefined behavior by accessing freed memory.

    You are basically asserting against garbage memory.