tags:

views:

112

answers:

4

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 );
}
+1  A: 

Maybe your application is multi-threaded and you are not locking insertion into map. Second variant doesn't share map with other threads.

ony
+2  A: 

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.

Kotti
Ok. Thanks. I'll have a look into it. The code is a bit too long to paste here.
Jakub Czaplicki
Yes. You were right. I had MapFile::LoadMapFile( filename ); instead of MapFile a; a.LoadMapFile(); It seems that my problem is fixed now.
Jakub Czaplicki
+2  A: 

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

R Samuel Klatchko
+1  A: 

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.

Bill Casarin