Here is the code which converts a hex string to byte array, it works fine but when the loop goes end and the complier reaches to the end of function it throws this error: "Stack around the variable 'uChar' was corrupted"
void Cfsp::stringToHex(unsigned char hexArray[], LPCTSTR string)
{
int stringLength=strlen(string);
int j=0;
unsigned char uChar = 0;
for (int x = 0; x < stringLength; x+=2)
{
sscanf_s(&string[x], "%02x", &uChar);
hexArray[j] = uChar;
j++;
}
}
Here is where I initiate the array and call the function.
unsigned char Key[16];
stringToHex( Key,"2f145a8b11d33217");
I know when stringToHex would convert the given string (16 chars length) to byte array it only fills 8 Bytes(as char). I just wanted to make a reserved area in the buffer.
This is why the xxx_s functions are not safe :-) People can misuse these safe functions as easily as the so-called "unsafe" ones.
sscanf with the %x format specifier wants an int pointer, not a char one.
It will write the entire (for example) 32 bit value starting at uChar and not caring one bit what it overwrites in the process.
It's only because you have stack protection enabled that the code catches this.
You should be using something like:
void Cfsp::stringToHex (unsigned char hexArray[], LPCTSTR string) {
int stringLength = strlen (string);
int j = 0;
unsigned int uChar = 0; // <-- INT rather than char.
for (int x = 0; x < stringLength; x+=2) {
sscanf_s (&string[x], "%02x", &uChar);
hexArray[j] = uChar;
j++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With