• Advertisement
Sign in to follow this  

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

This topic is 1401 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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. :-)

Edited by Dissipate

Share this post


Link to post
Share on other sites
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();
	}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

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?

Edited by Javier Meseguer de Paz

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites


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.
 

Share this post


Link to post
Share on other sites
You're crashing well within CFileText's destructor. Maybe the error is in the destructor itself. Edited by Pink Horror

Share this post


Link to post
Share on other sites

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?

Edited by Dissipate

Share this post


Link to post
Share on other sites

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.*/

}

Share this post


Link to post
Share on other sites

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?

Edited by Dissipate

Share this post


Link to post
Share on other sites
Where's the code that uses the smart pointers? My guess is that you're doing something bad with them, maybe in CloseIO.

Share this post


Link to post
Share on other sites

No I cant see anywhere that I'm freeing anything or doing anything bad. The rest of the code is all operator<< stuff. Working on piping stuff to the streams. Here is CloseIO():

.

	inline void CloseIO(void) override
	{
		if (m_ofs.is_open())
			m_ofs.close();

		if (m_ifs.is_open())
			m_ifs.close();
	}

.

Not calling it at the end of main() still produces the error. I am currently scanning http://www.gamedev.net/blog/355/entry-2254834-oh-noes-my-code-is-teh-crash/ to see if it enlightens me towards improving my debugging skills. That book that the previous link explicitly alluded to, at the end, sounds worth getting. I was thinking that maybe boost::archive::textoarchive needed the std::ofstream somehow during its destruction but that theory is out as I stopped the closing of the streams before destruction. I think the boost docs say that it automatically closes the associated stream on exit. But don't qoute me on that.

Share this post


Link to post
Share on other sites

Good morning...

Ok I've solved it fully and finally...!!!

 

I was sleeping and in my dream I dreamed that the shared pointer depended on the fstream(s). The static ofstream and ifstream were created after the shared pointers! I simply moved them to the top,  et voila, no more access violation.

 

Thank you Jesus!

Share this post


Link to post
Share on other sites

Good morning...

Ok I've solved it fully and finally...!!!

 

I was sleeping and in my dream I dreamed that the shared pointer depended on the fstream(s). The static ofstream and ifstream were created after the shared pointers! I simply moved them to the top,  et voila, no more access violation.

 

Thank you Jesus!

If you can use C++11 in your project, Meyers's singleton is simple, elegant, and thread-safe.

Share this post


Link to post
Share on other sites

 

 

If you can use C++11 in your project, Meyers's singleton is simple, elegant, and thread-safe.

 

 

Be careful with the thread-safety part.

 

Visual Studio 2012+ implements C++11  (well, partially, like many compilers) and thread-safe static initialization is NOT implemented: http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx .

 

 

Great point, I didn't know that VS has yet to implement this. Also, you get an upvote for knowing and applying the "Know thy standard" rule.

Share this post


Link to post
Share on other sites


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.

Would creating a "log manager" for managing multiple log object instantiations convince you to make the log manager a singleton?

Share this post


Link to post
Share on other sites

I was sleeping and in my dream I dreamed that the shared pointer depended on the fstream(s). The static ofstream and ifstream were created after the shared pointers! I simply moved them to the top,  et voila, no more access violation.


Oh, of course! Your reset calls worked because they released the pointers before the implicit destructor calls.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement