• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Dissipate

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

18 posts in this topic

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
0

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.
0

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
1

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.

0

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.
 

0

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
0

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
0

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

}
0

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
0

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.
0

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.

0

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!

1

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.

0

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.

0

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?

0

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.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0