Can't delete static singleton pointer (a deinitialization fiasco)

Started by
17 comments, last by Pink Horror 10 years, 1 month ago

EDIT: Solved see post #13

Hi I have successfully created singleton with a Logging function that works well if I let it leak - but upon deleting the s_pLogInstance, statically newed, object it crashes (no matter where I delete it. - except for right after i create it in the same function): Is it the method by which I access it. Although unlikely, am I recreating it before I destroy it?


Unhandled exception at 0x51E8F069 (msvcp110d.dll) in DXTB.exe: 0xC0000005: Access violation reading location 0xFEEEFEEE.

Even if I delete the log (pLogInstance) before the singleton (CEngine). I create the CEngine object first then log.

Here is CEngine.h...


#define CENGINE CEngine::GetInstance()

class CEngine
{
public:
	~CEngine(void) {}

	static void Destroy(void)
	{
		delete &CEngine::GetInstance();
		delete &(CEngine::GetInstance().GetLog()); // <== CRASH HERE pLogInstance is FEEEFEEE
	}

	static CEngine& GetInstance(void)
	{	
		static CEngine* s_pEngineInstance = new CEngine(); // Runs only once
		return *s_pEngineInstance;
	}

	ISerialization& GetLog(void) 
	{
		static ISerialization* s_pLogInstance = new CFileText(); // Runs only once
		return *s_pLogInstance;
	}

	static void __cdecl DestroyLog(void) // Can't call this from atexit() -dunno how...!
	{
		delete &CEngine::GetInstance().GetLog();
	}

	std::string GetDate(void);
	std::string GetTime(void);

protected:
	CEngine(void) // Hidden constructor
	{	
		GetLog() << "CEngine::CEngine() Created."; // Create log before CEngine to ensure destructor comes after CEngine.
	} 

private:
	// PRIVATE SEMANTICS
	CEngine(const CEngine& other) {}                     // Copy constructor
	friend void swap(CEngine& first, CEngine& second) {} // Swap implementation
	CEngine& operator=(CEngine other) {}                 // Assignment operator
	CEngine(CEngine&& other) {}                          // Move constructor
};

...and main() is effectively this (near enough)...


int main(void)
{
	CEngine::GetInstance();

	CENGINE.GetLog().OpenOutput(sLogFilename, std::ios::trunc);
	CENGINE.GetLog() << "CEngine::Create(): '" << sLogFilename << 
						"' started on: " << CENGINE.GetDate() << 
						" at: " << CENGINE.GetTime() << std::endl;

	CENGINE.GetLog() << std::endl;
	CENGINE.GetLog().CloseIO();
	
	CENGINE.Destroy();

	//atexit(CEngine::DestroyLog()); // <== I cant make this work either. 'static void DestroyLog(void) {}'

	//std::cin.get();
	return 0;
}

Hmm I know I really should handle exception elegantly but I'm just getting the hang of things. Advice would be appreciated. All help is graciously praised for. :-)

Advertisement

Haven't you just destroyed the instance that is returned by GetInstance() when you then ask for the log? Perhaps try reversing the order of those two statements?

e.g.


	static void Destroy(void)
	{
		delete &(CEngine::GetInstance().GetLog());
		delete &CEngine::GetInstance();
	}

Justin Stenning | Blog | Book - Direct3D Rendering Cookbook (using C# and SharpDX)

Projects: Direct3D Hook, EasyHook, Shared Memory (IPC), SharpDisasm (x86/64 disassembler in C#)

@spazzarama

 
Does ISerialization have a virtual destructor?

Also, why is the log a singleton instead of a member of the engine class? If you're going to get it by doing CEngine::GetInstance().GetLog(), it shouldn't be in any form of static.

I'm with spazzarama. After delete &(CEngine::GetInstance()) doing CEngine::GetInstance() again in the following line looks like a pretty bad idea....

Anyway, what lead me to post was to tell you that the 0xFEEEFEEE value is a good clue as to what is happening. If you know what you are looking at smile.png

0xFEEEFEE is a 'helper' value that the Debug CRT Heap uses to tell you that memory has already been freed. Just the same way that new memory gets initialized with 0xCDCDCDCD so that if you see that value you know you forgot to initialize something.

Look at for more information if you want: http://www.nobugs.org/developer/win32/debug_crt_heap.html.

PS: Are you sure that the value 0xFEEEFEEE is the value of pLogInstance and not the one returned by CEngine::GetInstance() because you delete it earlier?

“We should forget about small efficiencies, say about 97% of the time; premature optimization is the root of all evil” - Donald E. Knuth, Structured Programming with go to Statements

"First you learn the value of abstraction, then you learn the cost of abstraction, then you're ready to engineer" - Ken Beck, Twitter

Seems very suspicious.

Logging is a process where you generally have one well-known object. Then you register listeners to the object. Over time, various sources send data to the instance and it gets forwarded to all the listeners.

You might be able to make a case for a single global instance of a well-known logging class, but you won't convince me to make the logging class a singleton. Sometimes you might want to create a smaller log, an object specific to your component rather than being globally accessible, and attach a log listener to it.

I personally tend to like lots of logging listeners. A plain-text log writer that just dumps the facts to a file. A fancy HTML or XML log written to files for perusal later. An in-game log viewer that shows entries on screen. A network-based log system that lets me log when I run on a console or other device.

It seems like that is exactly what you have in this case. CEngine has a member variable of some custom type. In your case it is a stream, because that is what you have written. That is fine, you can make a class that accepts operator<<() and behaves properly.

When you start building up the parts of your CEngine object, you create your logging object. You can then register zero or more listeners to it. One listener might be a file stream, which seems to be what you are doing. When time comes to clean up you remove all of your listeners, each one closing their own streams.


Haven't you just destroyed the instance that is returned by GetInstance() when you then ask for the log? Perhaps try reversing the order of those two statements?

@spazzarama #Thanks:

Yes I'm sorry that was the result of me, frustratingly and unsystematically, switching lines of code about. I reversed the statements and the same error occurs. It even occurs if I try to call it from anywhere in main().


Does ISerialization have a virtual destructor?

@ Pink Horror #Thanks:

Yes ISerialization is a pure virtual interface that contains no data members - only 0 value virtual functions, including a virtual destructor. These are overriden successfully by CFileText and CFileBinary.


Also, why is the log a singleton instead of a member of the engine class?

Changing it to be a member of the class doesn't work wither - I get the same error! But I kinda agree with you maybe it should be a member.


PS: Are you sure that the value 0xFEEEFEEE is the value of pLogInstance and not the one returned by CEngine::GetInstance() because you delete it earlier?

@Javier Meseguer de Paz #Thanks

I switched them back around and even made it a member of CEngine and instatiated the pointer in the initialization of CEngine and it still holds that value. Also I checked the address of, now m_pLogInstance, and it is the same from creation to the point before deletion - for example (0x004db330).

This is the callstack:


>    msvcp110d.dll!std::locale::locale(const std::locale & _Right) Line 324    C++
     msvcp110d.dll!std::basic_streambuf<char,std::char_traits<char> >::pubimbue(const std::locale & _Newlocale) Line 122    C++
     DXTB.exe!boost::archive::basic_streambuf_locale_saver<char,std::char_traits<char> >::restore() Line 59    C++
     DXTB.exe!boost::archive::basic_streambuf_locale_saver<char,std::char_traits<char> >::~basic_streambuf_locale_saver<char,std::char_traits<char> >() Line 57    C++
     DXTB.exe!boost::archive::basic_text_oprimitive<std::basic_ostream<char,std::char_traits<char> > >::~basic_text_oprimitive<std::basic_ostream<char,std::char_traits<char> > >() Line 111    C++
     DXTB.exe!boost::archive::text_oarchive_impl<boost::archive::text_oarchive>::~text_oarchive_impl<boost::archive::text_oarchive>() Line 85    C++
     DXTB.exe!boost::archive::text_oarchive::~text_oarchive() Line 102    C++
     DXTB.exe!boost::archive::text_oarchive::`scalar deleting destructor'(unsigned int)    C++
     DXTB.exe!boost::detail::sp_ms_deleter<boost::archive::text_oarchive>::destroy() Line 65    C++
     DXTB.exe!boost::detail::sp_ms_deleter<boost::archive::text_oarchive>::operator()(boost::archive::text_oarchive * __formal) Line 88    C++
     DXTB.exe!boost::detail::sp_counted_impl_pd<boost::archive::text_oarchive *,boost::detail::sp_ms_deleter<boost::archive::text_oarchive> >::dispose() Line 154    C++
     DXTB.exe!boost::detail::sp_counted_base::release() Line 103    C++
     DXTB.exe!boost::detail::shared_count::~shared_count() Line 375    C++
     DXTB.exe!boost::shared_ptr<boost::archive::text_oarchive>::~shared_ptr<boost::archive::text_oarchive>()    C++
     DXTB.exe!CFileText::~CFileText() Line 48    C++
     DXTB.exe!CFileText::`scalar deleting destructor'(unsigned int)    C++
     DXTB.exe!CEngine::Destroy() Line 48    C++
     DXTB.exe!main() Line 50    C++
     DXTB.exe!__tmainCRTStartup() Line 536    C
     DXTB.exe!mainCRTStartup() Line 377    C


Seems very suspicious.

@ frob #Thanks

hehe... Isn't that by Stevie Wonder... Oh no that's very superstitous.

RE: Observer-Listener pattern I am thinking and researching about what you said and will look at implementing that kinda structure once I plan it out.

You're crashing well within CFileText's destructor. Maybe the error is in the destructor itself.

The destructor is empty though.

Ahh ok I just realised I read it wrong... Its not m_pLogInstance that is FEEEFEEE its the variable in xlocale. How do I debug this?

Here is CFileText's class. Can you notice anything that would cause this bug?


class CFileText : public ISerialization
{
public:
	boost::shared_ptr<boost::archive::text_oarchive> m_spTxtOA; // Txt Out
	boost::shared_ptr<boost::archive::text_iarchive> m_spTxtIA; // Txt In
	ifstream m_ifs;
	ofstream m_ofs;
	unsigned int m_iBoostFlags;
	unsigned int m_iIOFlags;

	int m_i;

	int GetNumber(void) override { return m_i; }
	void SetNumber(int i) override {  m_i = i; }

	CFileText(void) {}
	~CFileText(void) {}

	void OpenOutput(std::string s, unsigned int m_iIOFlags) override 
	{
		// Open filestream
	}
        
        /* All other operator<< overloads etc.*/

}

I've got it... It was the smart pointers!!! I removed them and used raw ones instead:

.


	boost::archive::text_oarchive* m_pTxtOA; // Txt Out
	boost::archive::text_iarchive* m_pTxtIA; // Txt In
         
        /* etc. */

	~CFileText(void) 
	{
		delete m_pTxtIA;
		delete m_pTxtOA;		
	}

.

Initialised like this in OpenOutput():

.


m_spTxtOA = boost::make_shared<boost::archive::text_oarchive>(m_ofs, m_iBoostFlags);

.

Since the raw pointers worked I put the smart pointers back in and tried manually resetting them in the destructor:

.


	~CFileText(void) 
	{
		m_spTxtIA.reset();
		m_spTxtOA.reset();
	}

.

Why does this work. This defeats the whole point of smart pointers. I should be able to just let them fall of the stack at the end but something is going wrong. Is it something to do with the de-initialization order? Can anyone please comment on this?

This topic is closed to new replies.

Advertisement