Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map insert segmentation fault

Tags:

c++

stl

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 "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 );
}
like image 602
Jakub Czaplicki Avatar asked Feb 06 '26 02:02

Jakub Czaplicki


1 Answers

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.

like image 132
M. Williams Avatar answered Feb 09 '26 10:02

M. Williams