4

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;
}
4

2 に答える 2

4

問題はここにあります

char pChar;

itoa(iMod, &pChar, 10 );

itoa は、単一の文字ではなく文字の配列で動作します。

itoa ここで使用方法の例を見つけることができます。

また、とにかく を使用する場合は、関数itoa全体を回避して呼び出すことができますDecToHex()itoa

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

これで完了です。

于 2012-11-20T06:27:05.260 に答える
0

問題は itoa への呼び出しにあります

itoa(iMod, &pChar, 10 );

itoa は末尾にヌル文字を配置するため、2 文字の配列を渡す必要があります。試す

char pChar[2];

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

あなたのコードで itoa 呼び出しは index 変数に書き込んでしまいます。

于 2012-11-20T06:34:15.187 に答える