I'm having a debug only crash. I'm using Eclipse's gdb.
If I'm not failing reading it, the crash seems to occur when passing an object (not by reference nor pointer) to an interface method, precisely when copying a "many" (typedef std::list<boost::any> many;) member during it's copy constructor called to send a copy to the method.
I'm not using debug builds for boost, nor other external builds, just for the code I'm compiling, so, could this be the cause?
Any other ideas at what may be the cause?
class Message {
public:
static const int MAX_LEVEL=5;
Message(int type=0, int destination=0);
virtual ~Message();
int type;
int destination[MAX_LEVEL];
int level;
many message;
};
And the crashing sector, inside init() on Game3DWin: (Even though I'm building in Debug mode, there's no _DEBUG define since I didn't build the Debug binaries for the libs)
bool Game3DWin::init(){
#ifdef _DEBUG
pluginsCfg = "lib/plugins_d.cfg";
resourcesCfg = "res/resources_d.cfg";
#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32
pluginsCfg = "lib/pluginsWin.cfg";
resourcesCfg = "res/resources.cfg";
#else
pluginsCfg = "lib/plugins.cfg";
resourcesCfg = "res/resources.cfg";
#endif
ogreRoot=boost::make_shared<Ogre::Root>(pluginsCfg, "config.cfg");
if(!(ogreRoot->restoreConfig() || ogreRoot->showConfigDialog())){
return false;
}
window = ogreRoot->initialise(true, "Crewon CLASH!");
loadResourceCfgFile();
guiRenderer = &CEGUI::OgreRenderer::bootstrapSystem();
CEGUI::SchemeManager::getSingleton().create( "TaharezLook.scheme" );
CEGUI::System::getSingleton().setDefaultFont( "DejaVuSans-10" );
CEGUI::System::getSingleton().setDefaultMouseCursor( "TaharezLook", "MouseArrow" );
CEGUI::Window* myRoot = CEGUI::WindowManager::getSingleton().createWindow( "DefaultWindow", "_MasterRoot" );
CEGUI::System::getSingleton().setGUISheet( myRoot );
CRengine::Message msg=CRengine::Message( (int)CRengine::MESSAGE_TYPE::INPUT_INIT );
msg.message.push_front(window);
this->broadcaster.lock()->receiveMessage( msg ); //Crash here
//Unreached code due to crash
}
broadcaster is a pointer to Messageable, an interface.
class Messageable {
public:
virtual ~Messageable() {};
virtual bool receiveMessage(CRengine::Message) = 0;
};
broadcaster initialization (factory method to be able to store a "this" smart pointer):
Game3DWin* Game3DWin::create(boost::shared_ptr<CRengine::Messageable> caster, int processType, int order){
Game3DWin* temp= new Game3DWin(processType, order);
temp->broadcaster=caster;
bool success=temp->init();
if(!success){
delete temp;
temp=NULL;
}else{
temp->checkRoom(); }
return temp;
}
The above is called here:
bool MainManager::start( boost::shared_ptr<MainManager> thisMM ){
//Some code
boost::shared_ptr<Game3DWin> win;
win.reset( Game3DWin::create(thisMM, CRengine::MAIN_PROCESS_TYPES::PROCESS_GUI) );
//Some code
}
start() called from the main, which passes the pointer to MainManager
boost::shared_ptr<CRengine::MainManager> app =boost::make_shared<CRengine::MainManager>();
app->start(app);
Message implementation:
Message::Message(int type, int destination): type(type), level(0){
for(int ii=0;ii<MAX_LEVEL;ii++){
this->destination[ii]=-1;
}
this->destination[0]=destination;
}
Message::~Message() { }
window is Ogre::RenderWindow* from OGRE 3D open source rendering engine. I tried to cast it to (int) before pushing it into many in case it tried to call a destructor or something, but, still, same crash.
This is an extended comment, too long to fit in a comment.
Message lacks an implemented constructor and destructor. Either simplfy the class while confirming the problem still occurs, or expose that implementation to us.
window is a variable of unknown type. As the list of boost::any that you are reporting as crashing contains the window type, knowing what it is may just be somewhat useful.
this->broadcaster.lock() will be a null shared_ptr if the weak_ptr has gone away. Always, always, always do shared_ptr<foo> pFoo = this->broadcaster.lock(); then use pFoo (or whatever name) after checking that it is valid (evaluating it in a boolean context).
boost::weak_ptr<CRengine::Messageable> caster -- do you not know if this exists? You probably want a boost::shared_ptr here, so that the caster is at least known to exist during creation of the Game3DWin.
Same here: boost::weak_ptr<MainManager> thisMM -- probably should be a shared_ptr.
The issue was none of the aforementioned. It was caused by Eclipse being unable to clean. This was caused due to using "External Builder", mingw32-make.exe, which in the makefile ran a del <Filelist> and Windows7 seems to have some issue with this and it's parameters, so the clean did nothing.
Since I was working with Debug as active build, I got the crash due to lack of clean, but when I switched to Release it was unaffected since it had to mostly rebuild everything.
Manual delete of the contents of <project>/Debug and <project>/Release fixed the problem.
Related
I'm using /NODEFAULTLIB to disable CRT(C Runtime), however my constructor is not called, which ends up causing an error in std::map (Access violation) because it is not initialized properly, since std::map constructor it's not called.
Code compiled with LLVM 8.0.0, compiled in mode debug x86
class c_test
{
public:
c_test( int a ) // Constructor not called
{
printf( "Test: %i\n", a ); // Doesn't appear and breakpoint is not reached
}
void add( const std::string& key, const std::string& val )
{
_data[ key ] = val;
}
private:
std::map< std::string, std::string > _data;
};
c_test test{ 1337 };
int main()
{
test.add( "qwrqrqr", "23142421" );
test.add( "awrqw", "12asa1faf" );
return 1;
}
I've implemented my own functions new(HeapAlloc), delete(HeapFree), printf, memcpy, memmove, etc, and all are working perfectly, I have no idea why this happening.
Disabling the CRT is madness.
This performs crucial functions, such as static initialisation. Lack of static initialisation is why your map is in a crippled state. I would also wholly expect various parts of the standard library to just stop working; you're really creating a massive problem for yourself.
Don't reinvent little pieces of critical machinery — turn the CRT back on and use the code the experts wrote. There is really nothing of relative value to gain by turning it off.
I discovered the problem and solved, one guy from another forum said that I needed manually call constructors that are stored in pointers in .CRT section, I just did it and it worked perfectly
I just called _GLOBAL__sub_I_main_cpp function that calls my constructor and solved all my problems, thanks for the answers.
Considering the following example:
#include <wx/bitmap.h>
int main()
{
wxBMPHandler h;
wxImage::AddHandler(&h);
wxBitmap bm = wxBitmap(200, 200);
bm.SaveFile("file.bmp", wxBITMAP_TYPE_BMP);
return 0;
}
Since I'm only using h to call AddHandler() and not for anything else, I'd like to avoid defining it altogether and do the whole thing in one line. So I thought about replacing that with:
wxImage::AddHandler(&wxBMPHandler());
which compiles fine, but calling SaveFile() won't work then; WxWidgets will present an error stating "No image handler for type 1 defined" at runtime.
I guess the object created inside the function call is temporary, but I'm not sure about that. If not, what am I missing, and how can I avoid defining h?
It's worth noting that AddHandler() has the following signature:
static void AddHandler( wxImageHandler *handler );
[Update]
In response to M.M's comment saying:
wxImage::AddHandler(&wxBMPHandler()); should fail to compile, unless
that class has overloaded operator& for rvalues
Since I couldn't find a definition for operator& in WxWidgets' source code, I created this test project:
#include <iostream>
#include <string>
using namespace std;
string* address = nullptr;
void testing(string* input)
{
*input = "Something else entirely";
address = input;
}
int main()
{
testing(&string("Life is a test"));
cout << *address << endl;
cin.get();
return 0;
}
It compiles fine, and runs without any "hard error" - the only caveat is that nothing is shown in the screen - (*address).empty() returns true.
I even defined my own class to test with, instead of std::string and yielded the same behavior (no compiler error, no runtime error, but no output).
I also tried this one-liner, as suggested by aichao, without success:
wxImage::AddHandler(shared_ptr<wxBMPHandler>(new wxBMPHandler()).get());
I've never used wxWidgets before, but according to the wxWidgets version 3.1.1 API docs here, you should call wxImage::AddHandler using a heap-allocated handler object:
wxImage::AddHandler(new wxBMPHandler);
Therefore, there is no need for defining h. Also according to the docs, the memory for this handler object is managed by the wxWidgets framework. Specifically, the docs says that the handler is a
heap-allocated handler object which will be deleted by wxImage if it is removed later by RemoveHandler() or at program shutdown.
There is also the static member function wxImage::CleanUpHandlers() to delete all registered image handlers. According to the docs:
This function is called by wxWidgets on exit.
Therefore, you do not have to delete the handler yourself unless you specifically want to (i.e., to free up some memory).
Hope this helps.
In wxImage::AddHandler(&wxBMPHandler());, the lifetime of the temporary stop at the end of the expression, so you have dangling pointer.
In
wxBMPHandler h;
wxImage::AddHandler(&h);
wxBitmap bm = wxBitmap(200, 200);
bm.SaveFile("file.bmp", wxBITMAP_TYPE_BMP);
h outlives the call bm.SaveFile("file.bmp", wxBITMAP_TYPE_BMP);.
You will have similar issue with
{
wxBMPHandler h;
wxImage::AddHandler(&h);
} // End of life time of h
wxBitmap bm = wxBitmap(200, 200);
bm.SaveFile("file.bmp", wxBITMAP_TYPE_BMP);
I have dynamically created an Sensor object with new. However, when I try to use the object, it looks like the Sensor's members are uninitialized. I have verified that the creation and initialization of the object is successful. I don't believe this problem is due to the global object not being static but, changing it doesn't resolve the issue either.
class SensorModule
{
public:
SPI_BUS* spi;
ADX123* accel;
SENSOR* sensor2;
...
public:
SensorModule();
~SensorModule();
public:
sendCommand();
...
}
SensorModule::SensorModule()
{
spi = new SPI_BUS(1,2,3);
accel = new ADX123(spi,4);
sensor2 = new SENSOR(spi,5);
...// more initialization
}
void SensorModule::sendCommand(void){
accel->accelCommand(); // When I debug and stop here, I see that my "this"
// accel pointer are uninitialized
// however, the SensorModule object pointer is
// valid in the heap
}
main.cpp
SensorModule* pModule = NULL;
int main(void)
{
pModule = new SensorModule();
pModule->sendCommand();
...
for(;;)
{}
}
your code seems fine so far, although you have to be very careful to also call delete. In C++ you should usually use unique_ptr to make sure that the elements are deallocated.
Do you debug in debug or release mode? Release mode sometimes messes up some debug symbols. Do you change accel in the course of the constructor or with another method? There has to be something because accel is definitely initialized here. You might also step through the different lines of your constructor to check this.
inside my MFC (VC2010 SP1) project, I'm widely using a third party library to write some data in a database. This library is quite old (I've found it compiled for VS2005) and uses _variant_t to handle data.
In a particular case anyway I get a strange behaviour, I'll try to explain it:
// .h
struct myData
{
blastuff
CString strMyCode;
};
class MyClass
{
protected:
myData m_Foo;
};
// .cpp
// In OnInitDialog:
//...
TrdPartRecordset *pRS;
//...
pRS->GetFieldValue( _T("MyDBColumn"), m_Foo.strMyCode );
Now, I do my job and when user press OK, it's time to save to database and here start the problems:
// In OnOK
TrdPartRecordset *pRS;
//...
pRS->SetFieldValue( _T("MyDBColumn"), m_Foo.strMyCode );
Problem: if I do not modify m_Foo.strMyCode, I don't have any problem. What if I modify it? Well, if m_Foo.strMyCode does NOT contain ANY number, still have no problem.
Instead, when I have a number, I get a nasty error:
Unhandled exception at 0x77772d37 in Mosaico.exe: 0xC0000005: Access violation reading location 0x9d7077b7.
which is an attempt to read a deleted location. I've checked m_Foo in the watch and it's correct and valid, so I've digged into library source code:
BOOL TrdPartyRecordset::SetFieldValue(LPCTSTR lpFieldName, CString strValue)
{
_variant_t vtFld;
if(!strValue.IsEmpty())
vtFld.vt = VT_BSTR;
else
vtFld.vt = VT_NULL;
vtFld.bstrVal = strValue.AllocSysString();
BOOL bret = PutFieldValue(lpFieldName, vtFld);
SysFreeString(vtFld.bstrVal);
return bret;
}
What it happens is that vtFld is valid until SysFreeString and it get destroyed after it (I can see it proceding step-by-step with debugger), but ONLY WHEN I HAVE NUMBERS INTO strValue. This doesn't happen when strValue is pure alphabetical.
I've searched around the Internet and found that this kind of error happens when you double release a resource and so I've commented out SysFreeString and boom goes the dynamite: no more crashes.
Anyway is a better programmer than me so I guess that if he put that SysFreeString he had his reasons, moreover, this is the only part of my program where this mechanism crashes.
My question is: do I lose memory commenting out that SysFreeString?
Another one: do you have better solutions?
The reason is simple:
The memory is freed twice!
_variant_t has a destructor. Set the type to VT_BSTR. You also see the pojnter and type to VT_BSTR
After the function you call, you free the memory again and the destructor does the same.
The code should look like this:
_variant_t vtFld;
if(!strValue.IsEmpty())
vtFld = strValue;
else
vtFld.vt = VT_NULL;
return PutFieldValue(lpFieldName, vtFld);
I have a program in which, partly for informational logging, I output the names of some classes as they are used (specifically I add an entry to a log saying along the lines of Messages::CSomeClass transmitted to 127.0.0.1). I do this with code similar to the following:
std::string getMessageName(void) const {
return std::string(typeid(*this).name());
}
And yes, before anyone points it out, I realise that the output of typeinfo::name is implementation-specific.
According to MSDN
The type_info::name member function returns a const char* to a null-terminated string representing the human-readable name of the type. The memory pointed to is cached and should never be directly deallocated.
However, when I exit my program in the debugger, any "new" use of typeinfo::name() shows up as a memory leak. If I output the information for 2 classes, I get 2 memory leaks, and so on. This hints that the cached data is never being freed.
While this is not a major issue, it looks messy, and after a long debugging session it could easily hide genuine memory leaks.
I have looked around and found some useful information (one SO answer gives some interesting information about how typeinfo may be implemented), but I'm wondering if this memory should normally be freed by the system, or if there is something i can do to "not notice" the leaks when debugging.
I do have a back-up plan, which is to code the getMessageName method myself and not rely on typeinfo::name, but I'd like to know anyway if there's something I've missed.
Another solution is to correct the underlying problem. This is not really a memory leak, just a false report. The memory blocks allocated to the tyepinfo() and the name() string are assigned the wrong block type. It is probably not a good idea to "free" this memory, since an attempt will be made by the CRT to free it again. The good news is this was finally fixed in VS2012 (_MSC_VER 1700+).
Since this only applies to _DEBUG builds, the following may be a safer solution. The function _FixTypeInfoBlockUse() should be called as mentioned above just before exiting the module entry point (main, WinMain, etc.).
#if defined(_DEBUG) && (_MSC_VER >= 1000 && _MSC_VER <= 1699)
//
// Debug memory block header:
// o Borrowed from the Microsoft CRT to fix the false "memory leak" report
// when using typeinfo 'name' accessor in a _DEBUG build of the library.
//
struct _CrtMemBlockHeader
{
struct _CrtMemBlockHeader * pBlockHeaderNext;
struct _CrtMemBlockHeader * pBlockHeaderPrev;
char * szFileName;
int nLine;
#ifdef _WIN64
int nBlockUse;
size_t nDataSize;
#else
size_t nDataSize;
int nBlockUse;
#endif
long lRequest;
unsigned char gap[4];
};
static void __cdecl _FixTypeInfoBlockUse(void)
{
__type_info_node* pNode = __type_info_root_node._Next;
while(pNode != NULL)
{
__type_info_node* pNext = pNode->_Next;
(((_CrtMemBlockHeader*)pNode) - 1)->nBlockUse = _CRT_BLOCK;
if (pNode->_MemPtr != NULL)
(((_CrtMemBlockHeader*)pNode->_MemPtr) - 1)->nBlockUse = _CRT_BLOCK;
pNode = pNext;
}
}
#endif//defined(_DEBUG) && (_MSC_VER >= 1000 && _MSC_VER <= 1699)
I've just stumbled upon this issue trying to clean the log of VLD. Yes, this is a known bug, which is fixed in VC11 only. It exists in previous versions of MSVC including 2010. This bug appears only if you use MFC. If you use MFC as DLL instead of static library, the memory leak will still exist, but won't be detected.
There is a global cache of type_info names and it is not cleared (the excerpt from <typeinfo>):
struct __type_info_node {
void *_MemPtr;
__type_info_node* _Next;
};
extern __type_info_node __type_info_root_node;
The idea is to clear this cache. This function works for me:
#include <typeinfo>
void clear_type_info_cache()
{
__type_info_node* & node = __type_info_root_node._Next;
while(node)
{
if (node->_MemPtr)
{
delete node->_MemPtr;
}
__type_info_node* tempNode = node;
node = node->_Next;
delete tempNode;
}
}
Call clear_type_info_cache() before exit. You can register it with atexit
#include <cstdlib>
int WinMain(...)
{
atexit(&clear_type_info_cache);
...
}
or call it immediately before leaving WinMain
struct dummy_scope_exit
{
typedef void (*Fun)();
dummy_scope_exit(Fun f) : m_f(f) {}
~dummy_scope_exit() { m_f(); }
Fun m_f;
};
int WinMain(...)
{
dummy_scope_exit cleaner = &clear_type_info_cache;
...
}
As pointed out by Chris Parton in the comments, this appears to be a known bug, at least with the version of compiler I am using - upgrading to VC11 would correct the issue, if I were able to upgrade.
Attempting to delete the output of typeinfo::name() partially works:
std::string getMessageName(void) const
{
std::string typeStr(typeid(*this).name());
delete (typeid(*this).name());
return typeStr;
}
However there are still some memory leaks - I just noticed that previously I appeared to be getting two leaks per call (perhaps due to the classes being inside a namespace?). Using the above version of code, this went down to one leak per call.
Another solution that appears to work is to link in the dynamic version of the MFC libraries (yes, I'm using MFC, don't judge me), rather than the static version.
VS stores type info in a singly-linked list. The header of this list is accessible by an opaque structure accessible by name __type_info_root_node. Actually it is a SLIST_HEADER structure.
Win32 API has a set of concurrency-safe function to work with such structures.
To fix memory leaks report In your case you need to delete all nodes of this list.
#include <Windows.h>
#include <typeinfo>
#include <vld.h>
void ClearTypeinfoCache()
{
#ifdef _DEBUG
while (auto entry = InterlockedPopEntrySList(reinterpret_cast<PSLIST_HEADER>(&__type_info_root_node)))
{
free(entry);
}
#endif
}
int main()
{
atexit(ClearTypeinfoCache);
return 0;
}
Updated: VLD 2.5.1 does not report memory leaks on type_info::name() in VS2015 Update 3.