unit testing - Google mock global object triggers a segmentation faultmemory leak - Stack Overflow

admin2025-04-23  5

I have the following setup for unit testing using googletest/gmock.

class MockClass{
public:
    MOCK_METHOD0(log, void()); // -> this is fine
    MOCK_METHOD3(fcntl, int(int fd, int cmd, void* lock));
    MOCK_METHOD1(close, int(int fd)); // -> this is fine

};

MockClass* mocks = nullptr;

extern "C" {
    // ...
    int fcntl(int fd, int cmd, void* lock) {
        return mocks->fcntl(fd, cmd, lock);
    }
    int close(int fd) { return mocks->close(fd);}
    // ...
}

class TestClass: public ::testing::Test {
protected:
    // Per-test-case set-up, called before the first test in this test case
    static void SetUpTestCase() {}

    // Per-test-case tear-down, called after the last test in this test case
    static void TearDownTestCase() {}

    // set-up logic as usual
    void SetUp() override {
        mocks = new MockClass();
    }
 
    // pre-test tear-down logic as usual
    void TearDown() override {
        delete mocks;
        mocks = nullptr;
    }
};

When running the tests, all pass, but at the end(I assume when the breakdown happens), I get a segmentation fault that I've isolated to the return mocks->fcntl(fd, cmd, lock); instruction inside the mock class. Doing a frame inspection in gdb-multiarch, it seems that this function is also called from this context:

and it definitely is not ok since the mock object is destroyed at this point. Why is this gcov library calling this function and how can I avoid or fix this problem because I also have it in another text executable.

Many thanks!

转载请注明原文地址:http://anycun.com/QandA/1745377418a90641.html