Sunday, April 22, 2018

c++ - Double free in Google Mock



I'm a newbie in Google Test and Mock framework.



I just try to run "Turtle" example, it was successful.




However, error message was displayed : double free or corruption (!prev).



MockTurtle.h



#include 

class MockTurtle : class Turtle {
MOCK_METHOD0(PenUp, void());
MOCK_METHOD0(PenDown, void());
MOCK_METHOD1(Forward, void(int distance));

MOCK_METHOD1(Turn, void(int degrees));
MOCK_METHOD2(GoTo, void(int x, int y));
MOCK_CONST_METHOD0(GetX, int());
MOCK_CONST_METHOD0(GetY, int());
};


Turtle.h



class Turtle {

virtual ~Turtle() {}
virtual void PenUp() = 0;
virtual void PenDown() = 0;
virtual void Forward(int distance) = 0;
virtual void Turn(int degrees) = 0;
virtual void GoTo(int x, int y) = 0;
virtual int GetX() const = 0;
virtual int GetY() const = 0;
};



Painter.h



class Painter    
{
       Turtle* turtle;
public:
       Painter( Turtle* turtle )
               :       turtle(turtle){}


       bool DrawCircle(int, int, int){
               turtle->PenDown();
               return true;
       }
};    


Main_test.cpp



#include 

#include
#include "Painter.h"
#include "MockTurtle.h"

using ::testing::AtLeast;

TEST(PainterTest, CanDrawSomething) {
 MockTurtle turtle;
 EXPECT_CALL(turtle, PenDown())
     .Times(AtLeast(1));


 Painter painter(&turtle);

 EXPECT_TRUE(painter.DrawCircle(0, 0, 10));
}

int main(int argc, char** argv) {
 // The following line must be executed to initialize Google Mock
 // (and Google Test) before running the tests.
 ::testing::InitGoogleMock(&argc, argv);

 return RUN_ALL_TESTS();
}    


Result



[==========] Running 1 test from 1 test case.    
[----------] Global test environment set-up.
[----------] 1 test from PainterTest
[ RUN      ] PainterTest.CanDrawSomething

[       OK ] PainterTest.CanDrawSomething (0 ms)
[----------] 1 test from PainterTest (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[  PASSED  ] 1 test.
*** Error in `/home/user/workspace/google_mock_2/Debug/google_mock_2': double free or corruption (!prev): 0x098a8080 ***


I tried to google, saw several same problems. People said that should not use mock as global variable.




But my example did not use global variable.



Please help me explain why double free happen.
Thanks in advance!


Answer



Last time, I built google test and google mock in SHARED library.
And error (double free) happened.



I have tried to build as STATIC library. This error no longer appear.
I don't know why but I will investigate to know more detail.



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...