Jump to content

  • Log In with Google      Sign In   
  • Create Account

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


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
18 replies to this topic

#1 Dissipate   Members   -  Reputation: 345

Like
0Likes
Like

Posted 19 March 2014 - 05:41 PM

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, 21 March 2014 - 04:08 AM.


Sponsor:

#2 spazzarama   Members   -  Reputation: 729

Like
3Likes
Like

Posted 19 March 2014 - 05:54 PM

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, EasyHookAfterglow, C#raft

@spazzarama

 

#3 Pink Horror   Members   -  Reputation: 1201

Like
0Likes
Like

Posted 19 March 2014 - 05:55 PM

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.

#4 Javier Meseguer de Paz   Members   -  Reputation: 371

Like
1Likes
Like

Posted 19 March 2014 - 08:30 PM

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, 19 March 2014 - 08:41 PM.

“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


#5 frob   Moderators   -  Reputation: 21176

Like
0Likes
Like

Posted 19 March 2014 - 10:48 PM

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.


Check out my personal indie blog at bryanwagstaff.com.

#6 Dissipate   Members   -  Reputation: 345

Like
0Likes
Like

Posted 20 March 2014 - 05:43 PM


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.
 



#7 Pink Horror   Members   -  Reputation: 1201

Like
0Likes
Like

Posted 20 March 2014 - 08:21 PM

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

Edited by Pink Horror, 20 March 2014 - 08:22 PM.


#8 Dissipate   Members   -  Reputation: 345

Like
0Likes
Like

Posted 20 March 2014 - 08:23 PM

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, 20 March 2014 - 08:36 PM.


#9 Dissipate   Members   -  Reputation: 345

Like
0Likes
Like

Posted 20 March 2014 - 08:43 PM

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

}


#10 Dissipate   Members   -  Reputation: 345

Like
0Likes
Like

Posted 20 March 2014 - 09:06 PM

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, 20 March 2014 - 09:08 PM.


#11 Pink Horror   Members   -  Reputation: 1201

Like
0Likes
Like

Posted 20 March 2014 - 09:16 PM

Where's the code that uses the smart pointers? My guess is that you're doing something bad with them, maybe in CloseIO.

#12 Dissipate   Members   -  Reputation: 345

Like
0Likes
Like

Posted 20 March 2014 - 09:32 PM

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.



#13 Dissipate   Members   -  Reputation: 345

Like
1Likes
Like

Posted 21 March 2014 - 04:06 AM

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!



#14 georger.araujo   Members   -  Reputation: 817

Like
0Likes
Like

Posted 21 March 2014 - 04:35 AM

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.



#15 Javier Meseguer de Paz   Members   -  Reputation: 371

Like
2Likes
Like

Posted 21 March 2014 - 08:20 AM

 

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 .


“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


#16 Dissipate   Members   -  Reputation: 345

Like
0Likes
Like

Posted 21 March 2014 - 08:32 AM


thread-safe static initialization is NOT implemented

 

So are 'boost::smart_pointers' the key? This guy says they are thread safe. (Qoute from boost docs contained)


Edited by Dissipate, 21 March 2014 - 08:32 AM.


#17 georger.araujo   Members   -  Reputation: 817

Like
0Likes
Like

Posted 21 March 2014 - 08:59 AM

 

 

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.



#18 TheComet   Members   -  Reputation: 1568

Like
0Likes
Like

Posted 21 March 2014 - 11:32 AM


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?


YOUR_OPINION >/dev/null


#19 Pink Horror   Members   -  Reputation: 1201

Like
0Likes
Like

Posted 21 March 2014 - 09:05 PM

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.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS