C ++. Variable wrapping is damaged.

I get the following error from the code I wrote - Runtime Check Error # 2 - Zeroing the stack around the variable "pChar"

From the research, it suggests that the problem is related to pHexValueBuffer = new char [256], and memset, and how I use true, to store values ​​for returning a hexadecimal number instead of a decimal. My research shows that somehow I go beyond the memory that I installed, just not understanding how to do it.

Any suggestions for fixing the problem?

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
source share
2 answers

Problem here

 char pChar; itoa(iMod, &pChar, 10 ); 

itoa works with more than one character array.

You can find examples of using itoa here .

Also, if you intend to use itoa anyway, you can avoid the entire DecToHex() function and 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're done.

+4
source

The problem is calling itoa

 itoa(iMod, &pChar, 10 ); 

itoa will put char zero at the end - so you need to pass an array of 2 characters. try

 char pChar[2]; ... itoa(iMod,pChar,10); 

With your code, the itoa call would end up writing to the index variable.

0
source

Source: https://habr.com/ru/post/1447139/


All Articles