Access Violation - dereferenced ostringstream

0

I have a ostringstream object that I am trying to insert some characters into, but the ostringstream object is in a shared_ptr called pOut. When I try to dereference pOut, I always get an Access Violation error.

This is a simplified version of what I am trying to do:

#include <iostream>
#include <sstream>

int main()
{
  std::shared_ptr<std::ostringstream> pOut;
  *pOut << "Hello";
  std::cout << pOut->str();
}

In my head this should work because the program seen below compiles and runs with no issues:

#include <iostream>
#include <sstream>

int main()
{
  std::ostringstream out;
  out << "Hello";
  std::cout << out.str();
}

How come dereferencing the object raises an Access Violation error, and how can I solve this problem? Below is the error I am getting.

Exception thrown at 0x00A22112 in MemoryIssueTest.exe: 0xC0000005: Access violation reading location 0x00000000.

c++
shared-ptr
access-violation
ostringstream
memory-access
asked on Stack Overflow Sep 25, 2020 by bmb • edited Sep 28, 2020 by M--

1 Answer

1

You created the pointer object, but it set to nullptr or NULL or 0 initially. So accessing that memory would surely and certainly cause segmentation fault or access violation. You need to give a value to it. So instead of this:

std::shared_ptr<std::ostringstream> pOut;

Use this:

std::shared_ptr<std::ostringstream> pOut = std::make_shared<std::ostringstream>();

This should solve your problem.

answered on Stack Overflow Sep 26, 2020 by Akib Azmain • edited Sep 28, 2020 by Akib Azmain

User contributions licensed under CC BY-SA 3.0