Is Debugbreak() occupies memory in c++?

186 Views Asked by At

When I want to new an object in C++, I need to consider what should I do when there is not enough memory, so I wrote the following code:

CacheHeapItem* m_Items;
try{
    m_Items = new CacheHeapItem[m_Count];
}catch(const bad_alloc& e){
    DebugBreak();
}

But I am not sure if the DebugBreak function will be executed when there is insufficient memory?

2

There are 2 best solutions below

2
On

If you use microsoft compiler use __debugbreak() which is functionally identical to DebugBreak() winapi function. It's unlikely that it allocates any memory, as it simply inserts __asm 3 opcode (for x86 and equivalent opcode on arm).

This is obviously not the best code for release, you may check for debugger presence and break only if IsDebuggerPresent:

CacheHeapItem* m_Items;
try{
    m_Items = new CacheHeapItem[m_Count];
}catch(const bad_alloc& e){
    if (IsDebuggerPresent())
        __debugbreak();
}
0
On

If you want to catch some exceptions you should configure exception filters. This way you won't need to write any special debug handling code that must be removed in release build (DebugBreak will cause process to be terminated if no debugger is present).