-3

Segmentation fault when calling expectation on a function that return a pointer.

data.h

struct Data
{
    int age;
    Data();
    ~Data(){}
};

master.h

class Master
{
    private: 
        Data *m_data;
    public:
        Data* getData() const {return m_data;}
};

master.cc

Master::Master()
{
    Data *m_data = new Data();
}

user.cc <<------------CLASS TO BE TESTED

...
Master masterRef;
masterRef.getData()->age = 10;      <---- How set call expectation on this line?

masterMock.h

class MasterMock
{
    MOCK_CONST_METHOD0(getData(), Data*());
};

testUser.cc

...
TEST_F(TestUser, test1)
{
    MasterMock masterMockRef;
    EXPECT_CALL(masterMockRef, getData()); <---- HERE IT CRASHES with segmentation fault.
}
273K
  • 29,503
  • 10
  • 41
  • 64
dochoex
  • 191
  • 1
  • 3
  • 11

2 Answers2

1

You never initialize the m_data pointer! So ... if you are trying to access this pointer via the getData() method, your application will crash with an seg fault.

class Master
{
    private: 
        Data *m_data;
    public:
        Data* getData() const {return m_data;}
};

//user.cc  <<------------CLASS TO BE TESTED
...
Master masterRef;
masterRef.getData()->age = 10;      <---- How set call expectation on this line?

one possible solution would be to initialize the m_data Pointer in the constructor of your Master class and free/delete it in the destructor.

class Master
{
    private: 
        Data *m_data;
    public:
        Master() {m_data = new Data(); }
        ~Master() { delete m_data; }
        Data* getData() const {return m_data;}
};
Mr.Yellow
  • 197
  • 1
  • 8
0

You are expecting the call to get called but forget to return what us supposed to return.

So currently nothing is return and hence you are accessing invalid data pointer.

Data* data = new Data();
EXPECT_CALL(masterMockRef, getData()).WillOnce(Return (data)); 
Swapnil
  • 1,424
  • 2
  • 19
  • 30