Assert() and free() of memory #4562
Replies: 2 comments
-
To ensure memory is freed even if an assertion fails, you can use
Here's how to implement this: class MemoryManager {
public:
explicit MemoryManager(void* ptr) : ptr_(ptr) {}
~MemoryManager() { free(ptr_); }
private:
void* ptr_;
};
TEST(TestSuite, TestName) {
int rc = 0;
void *ptr = malloc(10);
ASSERT_NE(ptr, nullptr); // Check allocation
// Ensure memory is freed automatically when out of scope
MemoryManager mem_manager(ptr);
rc = func(ptr);
EXPECT_EQ(rc, 0); // Continue execution even if this fails
// No need for explicit free(ptr) as it will be handled by MemoryManager
} This ensures that memory is freed even if the test fails. |
Beta Was this translation helpful? Give feedback.
-
Thank you @Shriharsh-Deshmukh |
Beta Was this translation helpful? Give feedback.
-
Hello,
I wanted to explain my problem via the below code:
So if my assert on
rc
fails, then the memory won't be freed.How do i handle this situation?
Beta Was this translation helpful? Give feedback.
All reactions