From 287f46b220513dde292f47dc4eb7dd4647610123 Mon Sep 17 00:00:00 2001 From: Alessio Quaglino Date: Wed, 28 May 2025 09:25:45 -0700 Subject: [PATCH] Ensure last XML is freed after tests. This fixes undetected memory leaks in tests calling mj_loadXML. Additionally, a specific test for `mj_freeLastXML` is introduced. PiperOrigin-RevId: 764294041 Change-Id: I8b5a5683d8431ed920cdd52b06ad3515d8e19e14 --- test/fixture.h | 3 +++ test/xml/xml_api_test.cc | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/test/fixture.h b/test/fixture.h index cbb71d5f..0569579d 100644 --- a/test/fixture.h +++ b/test/fixture.h @@ -53,6 +53,9 @@ class MujocoErrorTestGuard { // By default, any MuJoCo operation which triggers a warning or error will // trigger a test failure. class MujocoTest : public ::testing::Test { + public: + ~MujocoTest() { mj_freeLastXML(); } + private: MujocoErrorTestGuard error_guard; }; diff --git a/test/xml/xml_api_test.cc b/test/xml/xml_api_test.cc index fdd1421b..d8b7a58c 100644 --- a/test/xml/xml_api_test.cc +++ b/test/xml/xml_api_test.cc @@ -199,5 +199,15 @@ TEST_F(MujocoTest, SaveXmlWithDefaultMesh) { mj_deleteModel(saved_model); } +TEST_F(MujocoTest, FreeLastXml) { + static constexpr char xml[] = ""; + mjModel* model = LoadModelFromString(xml, 0, 0); + ASSERT_THAT(model, NotNull()); + mj_deleteModel(model); + ASSERT_NE(mj_saveLastXML(nullptr, nullptr, nullptr, 0), 0); + mj_freeLastXML(); + ASSERT_EQ(mj_saveLastXML(nullptr, nullptr, nullptr, 0), 0); +} + } // namespace } // namespace mujoco