Code Apprentice
Code Apprentice

Reputation: 522

After padding a string with zeroes - it prints unspecified characters? (C++)

Basically, here, I'm trying to reverse an array, and convert the reversed int array into a string (I'm trying to write the equivalent of Java's BigInteger class in C++ - basically turning the input into big endian ordering, breaking down the operations, reversing the result back to little endian format, and returning the string).

And as you can see below, it outputs some strange characters (I think it's an out of range reference?) - but I'm not entirely sure what caused this output?

I would really appreciate if you could take a look at it:

Sample input

int a[] = {1, 2, 3};
int rA[3];

reverseIntArray(a, rA, 3);
string aString = intArrayToString(a, 3);

cout << aString << endl;

Console output

123\216\377

As you can see - it calculates the answer correctly, with the exception of the \277_\377.

I'll post the rest of the relevant functions:

reverseIntArray

void reverseIntArray(int array[], int reversedArray[], int arrayLength) {
    for (int i = 0; i < arrayLength; i++) {
        reversedArray[i] = array[arrayLength - 1 - i];
    }
}

intArrayToString

string intArrayToString(int digits[], int length) {
    //  convert int array to char array
    char digitsChar[length];


    for (int i = 0; i < length; i++) {
        digitsChar[i] = '0' + digits[i];
    }

    //  convert char array to string
    string intString(digitsChar);

    return intString;
}

I'm quite sure this is a subtle issue to do with pointers, but I'm still relatively new to C++ (migrating from Java) and I've stared at this for hours but haven't come up with any ideas.

Upvotes: 0

Views: 93

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

The std::string constructor you are using is assuming that the string you pass is properly terminated, which it isn't and that leads to undefined behavior as the std::string constructor goes beyond the end of the digitsChar array.

Three possible solutions:

  1. Make room for another character in the digitsChar array and terminate it:

    char digitsChar[size + 1];
    
    for (...) { ... }
    
    digitsChar[3] = '\0';
    
    string intString(digitsChar);
    
  2. Use another constructor where you pass the length of the character array:

    string intString(digitsChar, length);
    
  3. Append the characters directly to the string:

    string intString;
    
    for (int i = 0; i < length; i++) {
        intString += '0' + digits[i];
    }
    

There are of course other solutions as well, like for example using std::ostringstream.

Upvotes: 2

Related Questions