繁体   English   中英

C ++变量周围的堆栈已损坏

[英]C++ Stack around a variable is corrupted

我从我编写的代码中得到以下错误 - 运行时检查失败#2 - 变量'pChar'周围的堆栈已损坏

从研究中可以看出,问题与pHexValueBuffer = new char [256]和memset以及我如何使用veritable - 存储值以返回Hex数而不是Decimal有关。 我的研究表明,不知怎的,我已经超出了我设定的记忆范围,只是不了解方式。

有关如何解决问题的任何建议?

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

问题出在这里

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;

你完成了。

问题在于对itoa的调用

itoa(iMod, &pChar, 10 );

itoa将在末尾放置一个空字符 - 所以你需要传递一个包含2个字符的数组。 尝试

char pChar[2];

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

使用你的代码itoa调用最终会写入索引变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM