C++ - Smart Pointers - Access Violation Reading Location 0xDDDDDDDD

-1

I'm currently creating a test for a legacy code and stuck with this error message when running my test (see below):

Exception thrown at 0x0F5001EF (Control.dll) in sample.exe:
0xC0000005: Access violation reading location 0xDDDDDDDD.

I understand that 0xDDDDDDDD means code was trying to access an already deleted pointer. But what I do not understand is where it was 'prematurely' deleted.

I've kept it to the very bare minimum. Here is my code

CDevice::CDevice() 
{
    numLedRows = numLedCols = 0;
}

CDevice::~CDevice()
{
   std::cout << "destructor!" << std::endl;
}

HRESULT CDevice::Init(IDevice* control)
{
    HRESULT hr = S_OK;
    deviceCtl.reset(control);
    return hr;
}

where:

std::unique_ptr<IDevice>   deviceCtl;

And my test:

TEST_F(deviceControlTest, test2)
{
     sut_->Init(deviceMock_.get());
}

where

std::unique_ptr<CDevice> sut_;
std::unique_ptr<DeviceMock> deviceMock_;

and in SetUp...

sut_ = std::make_unique<CDevice>();
deviceMock_ = std::make_unique<DeviceMock>();

I have also tried using shared_ptr for DeviceMock, same behavior.

Is this something wrong with my code? Or is it my test?? Any suggestions will be greatly appreciated!

c++
pointers
googletest
asked on Stack Overflow May 27, 2019 by keechan • edited May 28, 2019 by keechan

1 Answer

0

I think you have double delete issue here: both deviceMock_ and deviceCtl are handling same pointer. It is deleted twice (doeasn't matter if for unique and shared ptr) once when CDevice dtor is called and it's member, including the smart ptr used and once when deviceControlTest dtor is called. Please note that in gtest the call order is always the same for each test: test suite ctor, test suite setup, test body, test suite teardown, test suite dtor). Options:

  1. Use shared_ptr and copy it inside Init (do not reset it, just assign deviceCtl = control;).
  2. Inject via unique_ptr using approach from this SO question.
answered on Stack Overflow Jun 14, 2019 by Quarra • edited Jun 14, 2019 by Quarra

User contributions licensed under CC BY-SA 3.0