Home > Net >  Why is my program accessing values of the binaryString array when I try to print "value"?
Why is my program accessing values of the binaryString array when I try to print "value"?

Time:02-05

#include <stdio.h>
#include <math.h>
void MakeBinaryString(char *outString, char valueToConvert)
{
    // Convert a 1-byte value to a string that shows its value in
    // binary. We do this by checking to see each bit is on and
    // if it is, setting the character value to '1' or '0' if not.
    for (int i = 0; i < 8; i  )
    {
        // Is the bit a 1?

        // The shifting is needed to quickly generate a power of 2
        // so that we check only 1 bit at a time, starting with bit 7 // and working its way down.
        if (valueToConvert & (1 << (7 - i)))
            outString[i] = '1';
        else
            outString[i] = '0';
    }
    outString[8] = '\0';
}
int main(void)
{
    char value = 5;
    char binaryString[6];
    MakeBinaryString(binaryString, value);
    printf("The binary equivalent of %d is %s\n", value, binaryString);
    return 0;
}

Output: The binary equivalent of 48 is 00000101

So the above code can be fixed if we increase size of binaryString array to 9. But I don't understand why value is being printed as 48. If I comment out the else block of MakeBinaryString then value is printed as 5. But with the else block, whatever value I set char value to, it is printing 48 or 49.

CodePudding user response:

In the code you show, you're writing outside the bounds of binaryString, accessing 9 elements when there are only 6. This invokes undefined behaviour, anything could happen.

The reason that you see 48 or 49 in this particular case is that memory just so happens to be laid out such that the out-of-bounds writes are corrupting value.

The numeric ASCII values of '0' and '1' are 48 and 49, respectively. When you write out of bounds, you're overwriting value with one of those.


It's important to note that what you're doing isn't allowed, and could lead to any behaviour. You just got lucky in that variables are organized on the stack in such a way that the only noticeable damage is to value. Building for a different platform, with a different compiler or with different compiler options, or adding more to the program could lead to different and arbitrary results, including (but not limited to) crashes and corruption of other data used in the program.

  •  Tags:  
  • Related