jeudi 25 août 2016

Segfault when using pointer to class with unordered_map as member

I am trying to implement my own class, which has an unordered_map as member. Now the strange thing is that I get a segmentation fault when I call a member function when using a pointer to my class, while everything is fine when I don't use a pointer.

I attached a minimal working example reproducing the issue. I use Ubuntu 14.04 with gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3), and compiled my code with g++ -std=c++11 TestClass.cc. Can you tell me what's wrong?

Thanks a lot!

TestClass.h:

#include <unordered_map>
#include <vector>
#include <iostream>

using namespace std;


// payload class, which is stored in the container class (see below)
class TestFunction {
  public:
    void setTestFunction(vector<double> func) {
      function = func;
    }
    void resize(vector<double> func) {
      function.resize(func.size());
    }
  private:
    vector<double> function;
};

// main class, which has an unordered map as member. I want to store objects of the second class (see above) in it
class TestContainer {
public:
  void setContainer(int index, TestFunction function) {
   cout << "Trying to fill container" << endl;
   m_container[index]=function; // <---------------- This line causes a segfault, if the member function is used on a pointer
   cout << "Done!" << endl;
  }
private:
  unordered_map<int,TestFunction> m_container;
};

Main program TestClass.cc:

#include <TestClass.h>

int main(void) {
  //define two objects, one is of type TestContainer, the other one is a pointer to a TestContainer
  TestContainer testcontainer1, *testcontainer2;

  // initialize a test function for use as payload
  TestFunction  testfunction;
  vector<double> testvector = {0.1,0.2,0.3};

  // prepare the payload object
  cout << "Setting test function" << endl;
  testfunction.resize(testvector);
  testfunction.setTestFunction(testvector);

  // fill the payload into testcontainer1, which works fine
  cout << "Filling test container 1 (normal)" << endl;
  testcontainer1.setContainer(1,testfunction);

  // fill the same payload into testcontainer2 (the pointer), which gives a segfault
  cout << "Filling test container 2 (pointer)" << endl;
  testcontainer2->setContainer(1,testfunction);

  return 0;
}

Aucun commentaire:

Enregistrer un commentaire