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.
You created the pointer object, but it set to
nullptr
orNULL
or0
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:Use this:
This should solve your problem.