MooseTech
MooseTech

Reputation: 11

C++ invalid argument at memory location error

Im trying to read a single byte from a binary file and convert it into a bitset, and print it to the console however the following code raises an error.

ifstream test(filePath, ios::in | ios::binary);
char * byte = new char;
test.read(byte, 1);
cout << std::bitset<8>(byte);

Unhandled exception at 0x757DA842 in program.exe: Microsoft C++ exception: std::invalid_argument at memory location 0x006FEBE4.

I cant seem to figure out what is wrong and have tried a variety of things, any idea how to fix this?

Thanks

Upvotes: 0

Views: 1141

Answers (2)

dqthe
dqthe

Reputation: 793

byte in the final line std::bitset<8>(byte) isn't a character but a pointer.

Edit to std::bitset<8>(*byte) than code new code should work.

Read this answer for more detail.

Upvotes: 0

Miles Budnek
Miles Budnek

Reputation: 30494

You need to dereference byte when passing it to std::bitset's constructor.


Take a look at the reference for std::bitset's constructors.

You seem to want to call constructor number (2) on that page:

bitset(unsigned long long)

To construct a bitset representing the bits of the char pointed to by byte.

You're actually calling constructor number (4) (with CharT = char):

template< class CharT >
explicit bitset(
    const CharT* str,
    typename std::basic_string<CharT>::size_type
        n = std::basic_string<CharT>::npos,
    CharT zero = CharT('0'),
    CharT one = CharT('1')
)

With the default std::string::npos for the second argument, this assumes the pointer passed as str points to a C-style nul-terminated string of '0' and '1' characters and tries to construct the bitset from those.

Upvotes: 2

Related Questions