added memory leak detection thread safety

clean up and and rebased from #418 
Would you mind not using a #define here. It makes it a bit hard to follow what is going on :)