Why does this code stop with segmentation fault :
class MapFile
{
public:
/* ... */
std::map <unsigned int, unsigned int> inToOut;
};
bool MapFile::LoadMapFile( const wxString& fileName )
{
/* ... */
inToOut.insert( std::make_pair(input,output) );
}
but when I put the "std::map inToOut;" just before "开发者_StackOverflow中文版inToOut.insert" it works just fine :
class MapFile
{
public:
/* ... */
};
bool MapFile::LoadMapFile( const wxString& fileName )
{
/* ... */
std::map <unsigned int, unsigned int> inToOut;
inToOut.insert( std::make_pair(input,output) );
}
?
OK. Thanks guys, it seems that I have fixed this issue thanks to your help.
The problem was in the part of the code where I've been calling the LoadMapFile :
void WizardProductPage::OnTestButtonMapFile( wxCommandEvent& event )
{
wxString filename;
filename = locMapFile->GetValue();
MapFile::LoadMapFile( filename );
}
Should be :
void WizardProductPage::OnTestButtonMapFile( wxCommandEvent& event )
{
wxString filename;
filename = locMapFile->GetValue();
MapFile mapFile;
mapFile.LoadMapFile( filename );
}
I guess your problem is somewhere else. The following code works ok:
class MapFile
{
public:
std::map <unsigned int, unsigned int> inToOut;
void LoadMapFile();
};
void MapFile::LoadMapFile()
{
inToOut.insert( std::make_pair(1, 1) );
}
int main() {
MapFile a;
a.LoadMapFile();
return 0;
}
Try step-by-step debugging or post your whole code here, because this has no problems in it.
Also, yes. If you're trying to do that operation from different threads simultaneosly without locking, it could cause segfault.
Most likely you have a buffer overflow or a bad pointer that has caused you to trash the map when it's a member of your class. When you have the class an an auto variable, it is somewhere else in memory and your original bug is trashing some other piece of memory.
You should run your code under a memory debugger. If you are on Linux, I would recommend Valgrind
Maybe your application is multi-threaded and you are not locking insertion into map
. Second variant doesn't share map
with other threads.
It's possible that you called the member function on a object that has been deleted.
eg.
MapFile *p;
{
MapFile a;
p = &a;
}
p->LoadMapFile("test.map");
Would produce the error you described. The second case would not since you are not dereferencing the this
pointer at any time.
edit: Maybe not, in the case that the input,output variables are member data then my answer would be incorrect.
Other reason for this kind of problem could be using a map with custom comparator and/or allocator and not initializing the map accordingly, which could generate segmentation faults at any random point, ie: the first insert could work perfectly, but on the second one, when the compare function is called, there could be a segmentation fault.
精彩评论