C++ 变量周围的堆栈已损坏
C++ Stack around a variable is corrupted
我从我编写的代码中收到以下错误 -运行时检查失败 #2 - 变量"pChar"周围的堆栈已损坏
从研究中可以看出,这个问题与 pHexValueBuffer = new char[256] 和内存集以及我如何使用真正的 - 存储值以返回十六进制数而不是十进制有关。我的研究表明,不知何故,我设置的记忆超出了界限,只是不明白如何。
关于如何解决问题的任何建议?
void DecToHex()
{
string input;
int total = 0;
int index = 254;
char pChar;
char* pHexValueBuffer = new char[256];
memset(pHexValueBuffer, 0, 256 );
pHexValueBuffer[255] = ' ';
cout << "Enter a Decimal Numbernn" << 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 Numbernn" << 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 调用最终会写入索引变量。
相关文章:
- gdb错误:Backtrace已停止:上一帧与此帧相同(堆栈已损坏?)
- 变量周围的堆栈'...'已损坏
- 运行时检查失败 #2 变量"A"周围的堆栈已损坏
- 运行时检查失败 #2 - 变量"e"周围的堆栈已损坏。发生
- 运行时检查失败 #2 - 变量周围的堆栈'...'已损坏
- 运行时检查失败 #2 - 变量"l1"周围的堆栈已损坏
- 数组变量周围的堆栈已损坏
- 运行时检查失败 - 变量周围的堆栈已损坏
- 调试:运行时检查失败 #2 - 变量"LoggerThread"周围的堆栈已损坏
- 运行时检查失败 #2 - 变量"数字选择"周围的堆栈已损坏
- 运行时间检查:变量周围的堆栈已损坏
- 变量"name"周围的堆栈已损坏C++
- MS 工作室 17 变量周围的堆栈已损坏
- 错误:运行时检查失败 #2 - 变量周围的堆栈已损坏
- C++指针:数组的堆栈已损坏
- 变量周围的堆栈已损坏
- C++ 变量周围的堆栈已损坏
- 运行时检查失败 #2 - 变量周围的堆栈---已损坏
- VS2010和OpenCV:变量周围的堆栈已损坏
- 指针函数参数已损坏,堆栈已损坏