c++stringchariterationstring-iteration

What is a properly way to iterate a char* string? Getting "corrupt" values


When I was trying to iterate a number (transformed to binary with bitset library) I managed this solution

#include <iostream>
#include <bitset>

void iterateBinary(int num) {
    char *numInBinary = const_cast<char*>(std::bitset<32>(num).to_string().c_str());

    for (int i = 31; i >= 0; i--) {
        char bit = numInBinary[i];
        std::cout << i << ": " << bit << std::endl;
    }
}

But founded those weird characters in the output

Weird output

I already implemented a solution to my initial idea with for (char bit : numInBinary) and without c_str() transformation, but I'm still curious about what happened (maybe memory problems?) or which can be a better way to iterate a char* string

Also remark that the "corrupt" values in the output are no the same on each ejecution and only appears at the end, why? Thanks in advance


Solution

  • The lifetime of the string returned by to_string(), and into which the pointer returned by c_str() points, ends at the end of the full expression.

    This means after the line

    char *numInBinary = const_cast<char*>(std::bitset<32>(num).to_string().c_str());
    

    the pointer numInBinary will be dangling and trying to access through it will result in undefined behavior.

    You need to store the return value from to_string() so that it lives long enough, e.g.

    auto numInBinary = std::bitset<32>(num).to_string();
    

    There is also no need for a char* pointer, since std::string can just be indexed directly.

    Also, if you think you need to use const_cast anywhere, rethink it. Except for very specific scenarios where you take care of const correctness by unusual means, const_cast is almost surely the wrong approach and likely to result in undefined behavior down the line.