C ++堆栈变量已损坏 [英] C++ Stack around a variable is corrupted

查看:824
本文介绍了C ++堆栈变量已损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

从研究中可以看出,问题与pHexValueBuffer = new char [256]和memset有关,我如何使用veritable - 存储值来返回十六进制数而不是十进制。我的研究表明,不知何故,我将走出与我设置的内存边界,只是不知道如何。

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


推荐答案

p>

The problem is here

char pChar;

itoa(iMod, &pChar, 10 );

itoa使用一个字符数组而不是一个字符数组。

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

您可以找到如何使用 itoa 此处

You can find examples of how to use itoa here.

此外,如果你还要使用 itoa ,你可以避免整个 DecToHex() function&只需调用 itoa

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;

完成了。

这篇关于C ++堆栈变量已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆