MFC › 8. Debugging and Maintenance
Debugging: ASSERT, TRACE and Leak Detection
Debug macros, afxDump and finding memory leaks.
Explanation
MFC ships a set of debug-only macros and classes. In a Debug build (_DEBUG defined, linked with the debug MFC library) they check and report; in a Release build they compile away.
| Facility | Purpose |
|---|---|
ASSERT(cond) |
if cond is false in Debug: dialog with file and line, then breakpoint. Removed in Release, so the expression is not evaluated there. |
VERIFY(expr) |
like ASSERT, but expr is still evaluated in Release (the result is ignored): use it for calls with side effects. |
ASSERT_VALID(pObj) |
calls the object’s AssertValid() (you override it to check invariants) |
TRACE(fmt, ...), TRACE0/1/2 |
printf-style text to the debugger’s Output window (OutputDebugString) |
ASSERT_KINDOF, ASSERT_POINTER, ASSERT_NULL_OR_POINTER |
checks types and pointers |
DEBUG_NEW |
with #define new DEBUG_NEW, remembers file/line of every allocation so memory leaks are reported at exit |
CMemoryState |
Checkpoint() before and after a block; Difference() tells you whether memory was leaked, DumpAllObjectsSince() lists the objects |
CObject::Dump(CDumpContext&) |
override to print an object’s state; afxDump << obj writes it to the debugger |
Leak report: when a Debug MFC program ends, the output window shows “Detected memory leaks!” with a list; with DEBUG_NEW each block shows the file and line of its allocation. Click the line to jump to the code. You can break at an allocation number with _CrtSetBreakAlloc(n).
The Visual Studio debugger complements this: breakpoints, data tips on CString/CArray (the Natvis visualizers show contents), the Call Stack window (with the message-map frames) and Output window for TRACE.
Example
#include <afxwin.h>
#ifdef _DEBUG
#define new DEBUG_NEW // allocation sites are recorded for leak reports
#endif
class CAccount : public CObject {
DECLARE_DYNAMIC(CAccount)
public:
CAccount(const CString& owner, double balance) : m_owner(owner), m_balance(balance) {}
void Withdraw(double amount) {
ASSERT(amount > 0); // precondition (programmer error, Debug only)
ASSERT(amount <= m_balance);
m_balance -= amount;
TRACE(_T("Withdrew %.2f from %s, %.2f left\n"), amount, (LPCTSTR)m_owner, m_balance);
}
bool Save() {
CFile f;
VERIFY(f.Open(_T("account.dat"), CFile::modeCreate | CFile::modeWrite)); // runs in Release too
return true;
}
#ifdef _DEBUG
void AssertValid() const override { // called by ASSERT_VALID
CObject::AssertValid();
ASSERT(!m_owner.IsEmpty());
ASSERT(m_balance >= 0);
}
void Dump(CDumpContext& dc) const override {
CObject::Dump(dc);
dc << "owner = " << m_owner << ", balance = " << m_balance << "\n";
}
#endif
private:
CString m_owner;
double m_balance;
};
IMPLEMENT_DYNAMIC(CAccount, CObject)
void Demo() {
CAccount* pAcc = new CAccount(_T("Ann"), 100.0);
ASSERT_VALID(pAcc); // invariants hold?
pAcc->Withdraw(30.0);
#ifdef _DEBUG
afxDump << *pAcc; // goes to the debugger Output window
CMemoryState before, after, diff;
before.Checkpoint(); // snapshot of the heap
CAccount* leaked = new CAccount(_T("Bob"), 5.0); // never deleted: a leak
after.Checkpoint();
if (diff.Difference(before, after)) {
TRACE0("Memory leaked between checkpoints!\n");
diff.DumpStatistics();
before.DumpAllObjectsSince(); // lists the leaked CAccount with file/line
}
(void)leaked;
#endif
delete pAcc;
}
Common pitfalls
- Side effects inside
ASSERT:ASSERT(file.Open(...))is not executed in Release, so the file is never opened. UseVERIFY. ASSERTis for programmer errors (broken invariants). Use real error handling (return codes, exceptions) for conditions that can occur at run time (missing file, bad user input).#define new DEBUG_NEWmust come after all other#includes; headers that define their ownnewor placement-new break otherwise (wizard files put it at the end of each .cpp).- Leaks reported at exit may be caused by objects still owned by static/global variables that haven’t been destroyed yet: not always real leaks.
- Mixing Debug and Release MFC libraries in one project gives crashes or link errors; all modules must use the same configuration.
- Never ship assumptions based on
TRACEoutput:TRACEand its arguments disappear in Release. - A
TRACEstring longer than 512 characters is truncated: useTRACEfor short messages.
Legacy vs modern
The CRT debug heap (_CrtDumpMemoryLeaks, _CrtSetDbgFlag) works without MFC, and static_assert (C++11) and smart pointers prevent whole classes of leaks. Sanitizers (AddressSanitizer is built into MSVC 2019+), std::source_location logging and Visual Studio’s diagnostic tools supersede some of it. Compare with Exceptions for run-time error handling.
Exercises
1. What is the difference between ASSERT(f()) and VERIFY(f()) in a Release build?
ASSERT(f()) removes the whole expression, so f() is not called. VERIFY(f()) still calls f() and just ignores the result.