Stack around the variable 'uChar' was corrupted
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);
hex开发者_如何学JAVAArray[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++;
}
}
The reason you get corruption is because you send sscanf_s
an unsigned char *
where it expects int *
I don't know how sscanf_s works, but from the sscanf manpage:
x Matches an unsigned hexadecimal integer; the next pointer must be a pointer to unsigned int.
The error is probably caused by "%02x"
which requires an int as storage, not an unsigned char.
The issue could also be that you called strlen(LPCTSTR)
. LPCTSTR
might or might not have a terminating zero, if it doesn't strlen
invokes undefined behaviour. Use _tcslen(LPCTSTR)
instead.
精彩评论