C++ Stack around a variable is corrupted

2019-06-25 12:45发布

问题:

I'm getting the following error from the code I've written - Run-Time Check Failure #2 - Stack around the variable 'pChar' was corrupted

From research it is suggestive that the problem has to do with pHexValueBuffer = new char[256] and the memset and how I'm using the veritable - to store values to return a Hex number instead of Decimal. My research suggests that somehow I'm going out of bounds with the memory I've set, just not understanding the how.

Any suggestions on how to fix the issue?

void DecToHex()
{
    string input;
    int total = 0;
    int index = 254;
    char pChar;
    char* pHexValueBuffer = new char[256];
    memset(pHexValueBuffer, 0, 256 );
    pHexValueBuffer[255] = '\0';

    cout << "Enter a Decimal Number\n\n" << flush;

    cin >> input;
    unsigned int iValue = atoi(input.c_str());


    do
    {
        --index;
        unsigned int iMod = iValue % 16;
        if( iMod > 9 )
        {
            switch (iMod)
            {
            case 10:
                pHexValueBuffer[index] = 'A';
                break;
            case 11:
                pHexValueBuffer[index] = 'B';
                break;
            case 12:
                pHexValueBuffer[index] = 'C';
                break;
            case 13:
                pHexValueBuffer[index] = 'D';
                break;
            case 14:
                pHexValueBuffer[index] = 'E';
                break;
            case 15:
                pHexValueBuffer[index] = 'F';
                break;
            default:
                break;
            }

        }
        else
        {
            itoa(iMod, &pChar, 10 );
            pHexValueBuffer[index] = pChar;
        }
        iValue = iValue/16;

    } while( iValue > 0 );

    cout << "Decimal Number = " << &pHexValueBuffer[index];
    delete []pHexValueBuffer;
    pHexValueBuffer = NULL;
}

回答1:

The problem is here

char pChar;

itoa(iMod, &pChar, 10 );

itoa works with an array of chars not a single one.

You can find examples of how to use itoa here.

Also if you are anyway going to be using itoa, you can avoid the whole DecToHex() function & just call itoa

int val;
char pHexValueBuffer[256]
cout << "Enter a Decimal Number\n\n" << flush;
cin >> val;
itoa(val, pHexValueBuffer, 16);
cout << "Hexadecimal Number = " << pHexValueBuffer;

And you are done.



回答2:

The problem is with the call to itoa

itoa(iMod, &pChar, 10 );

itoa will put a null char at the end - so you need to pass an array of 2 chars. try

char pChar[2];

...
itoa(iMod,pChar,10);

With your code itoa call would have ended up writing to index variable.