GLFW #define Issue When Using crtdbg.h


#1

In the program I’m working on, I am using crtdbg.h to identify memory leaks in my code. However, whenever I try to call glfwPollEvents(), I’m getting this error:

Exception thrown at 0xCDCDCDCD in [name].exe: 0xC0000005: Access violation executing location 0xCDCDCDCD

I know this is some sort of uninitialized heap memory error. After some testing, I figured out that this only occurred because of this:

#ifdef _DEBUG
 #define _CRTDBG_MAP_ALLOC
 #include <stdlib.h>
 #include <crtdbg.h>
 #define dbgnew new(_NORMAL_BLOCK, __FILE__, __LINE__)  // <- This #define is making glfwPollEvents error
#else
 #define dbgnew new
#endif

I don’t understand how this is making the error… The name of the #define is not the problem. I literally tried renaming it to aksdfjklasdjglkasdhgalks and it still errored. How the heck does me defining a macro for myself cause glfwPollEvents() to error?!

Thanks for any help.


#2

I figured it out. It was not GLFW (can’t say I’m surprised). The error was in my cursor position callback. It turns out that when you are in this debug mode for CRT, it is very picky about things that are nullptr. In other words, if you want to check if something is nullptr, you need to explicitly set it to nullptr first. A really strange error…


#3

That’s pretty normal and expected behavior. If you want variables to be with expected value, you need to initialize them. If you don’t initialize them then they will have undefined value. And that’s a bug in your code.

By undefined value I mean it can be NULL (or 0) or it can be 1, or 2 or any other number. Typically when you compile in debug mode or with special memory leak detection library then this debug code or debug library will pre-initialize memory with some special pattern. It can be 0xcccccccc or similar value, so you can spot it more easily in debugger. In release mode memory is not pre-intitialized so you’ll get whatever value was written there previously by your program (not your code, it could be some other library, or C runtime/startup code). Sometimes you’ll get 0/NULL, but that’s just a luck.

So pretty much never read values (or pass them to glfw or other library functions who will read those) from variables you have not initialized yet. Doing so is a bug.