Search code examples
c++heap-memorystd-bitset

How can I use a bitset on the heap in C++?


If i use a bitset on the stack i can do the following:

std::bitset<8> bset_s;
bset_s.flip(1);

std::cout << "Bitset on stack: " << bset_s << std::endl;
std::cout << "Element 1: " << bset_s[1] << std::endl;

Output:

Bitset on stack: 00000010
Element 1: 1

But when I try to allocate the bitset on the heap:

std::bitset<8> * bset;
bset = new std::bitset<8>;

bset->flip(1);


std::cout << "Bitset on heap: " << * bset << std::endl;
std::cout << "Element 1: " << bset[1] << std::endl;

Output:

Bitset on heap: 00000010
Element 1: 00000000

I get an empty Bitset instead of "1" if I try to access the second bit. What am I doing wrong?


Solution

  • bset[1] is equivalent to *(bset + 1) as bset is a pointer. This is dereferencing memory that you don't own, so the behaviour of the program is undefined.

    You need (*bset)[1].