c++boostsegmentation-faultboost-dynamic-bitset

dynamic bitset initialized and called from other method gives segmentation fault


I initialize a dynamic bitset in a constructor of a class and then call a method of that class to fill it with some values. I get a segmentation fault no matter which part of the bitset I try to access.

MyClass::MyClass()
{ 
  boost::dynamic_bitset<> occupancy(200000); // all 0's by default
  std::cout << occupancy.size() << "\n";
  std::cout << occupancy[1234] << "\n";
  fill_occupancy();
}

void MyClass::fill_occupancy()
{
  std::cout << occupancy[1234] << "\n";
}

The constructor prints out the correct output of 200000 and 0, but when enters the fill_occupancy methood it gives segfault.

I checked this question, but I don't think that applies, bc I construct the bitset properly as I see the correct output from the constructor.

I've found a way to make it work if I simply make the method fill_occupancy() to accept argument of type dynamic_bitset<> and then call it with fill_occupancy(occupancy). Why this works and the code above does not? Other data types I can call in other methods without having them as argument.

Thank you.

Edit This is in case someone would be interested in more detailed explanation:

class MyClass()
{ 
  boost::dynamic_bitset<> occupancy; //calls default bitset constructor (i.e size 0)
}

In the MyClass constructor, calling just

MyClass::MyClass()
{ 
  occupancy(200000); // this is WRONG
}

produces error as the occupancy is set to zero size. To resize it one has to call

MyClass::MyClass()
{ 
  occupancy.resize(200000); // this is CORRECT
}

Then occupancy has the correct size and is member of MyClass and as such can be accessed from any other method of the class such as fill_occupancy().

My original construction made the occupancy a local variable of the same name as the member one so in the constructor it worked but everywhere else the member (of size 0) was called which explains the segfault.

Thank again juanchopanza for explanations.


Solution

  • The constructor is instantiating a local bitset called occupancy, not a data member of the same name:

    boost::dynamic_bitset<> occupancy(200000); // local variable
    

    It seems like you want to initialize a data member, which you can do like this:

    MyClass::MyClass(): occupancy(200000)
    { 
      std::cout << occupancy.size() << "\n";
      std::cout << occupancy[1234] << "\n";
      fill_occupancy();
    }