Program crashes when using std::bitset but only when compiled with VC 2015

590 views Asked by At

I'm working on a simple program which converts strings into binary code and back. I'm working on Ubuntu and wanted to compile the program on Windows with Visual Studio 2015. While the Linux build runs fine, on Windows it compiles, but crashes with something like

bitset<N> char

when calling following function:

bool bin2string(std::string *psBinaryString, std::string *psCharakterString)
{
psCharakterString->clear();
char cTempArray[8];
char cTemp;

for(unsigned int i = 0; i < psBinaryString->length(); i += 8)
{
    for(unsigned int j = 0; j < 8; ++j)
    {
        cTempArray[j] = psBinaryString->c_str()[j + i];
    }
    std::bitset<8> Bitset(cTempArray);
    cTemp = static_cast<char>(Bitset.to_ulong());
    psCharakterString->push_back(cTemp);
}
return true;
}

Now, my questions are, what is wrong with this code? Why does it work on Linux (gcc) and Windows (MinGW), but not on Windows with Visual Studio 2015?

My current workarround for this is:

#ifdef _WIN32

bool bin2string(std::string *psBinaryString, std::string     *psCharakterString)
{
psCharakterString->clear();
char cTempArray[8];
char cTemp;

for(size_t i = 0; i < psBinaryString->length(); i += 8)
{
    for(size_t j = 0; j < 8; ++j)
    {
        cTempArray[j] = psBinaryString->c_str()[j + i];
    }
    cTemp = static_cast<char>(strtol(cTempArray, 0, 2));
    psCharakterString->push_back(cTemp);
}
return true;
}

#else

bool bin2string(std::string *psBinaryString, std::string *psCharakterString)
{
psCharakterString->clear();
char cTempArray[8];
char cTemp;

for(unsigned int i = 0; i < psBinaryString->length(); i += 8)
{
    for(unsigned int j = 0; j < 8; ++j)
    {
        cTempArray[j] = psBinaryString->c_str()[j + i];
    }
    std::bitset<8> Bitset(cTempArray);
    cTemp = static_cast<char>(Bitset.to_ulong());
    psCharakterString->push_back(cTemp);
}
return true;
}

#endif

Which one of these two solutions is better?

1

There are 1 answers

0
AudioBubble On

Your crash is caused by the fact that std::bitset's constructor expects either an array length, or a null terminated string.

(see the documentation at http://en.cppreference.com/w/cpp/utility/bitset/bitset)

So you should be using:

std::bitset<8> Bitset(cTempArray, 8);