When the following code is compiled with LLVM Compiler, it doesn’t operate correctly.
(i doesn’t increase.)
It operates correctly when compiling with GCC 4.2.
Is this a bug of LLVM Compiler?
#include <stdio.h>
#include <string.h>
void BytesFromHexString(unsigned char *data, const char *string) {
printf("bytes:%s:", string);
int len = (int)strlen(string);
for (int i=0; i<len; i+=2) {
unsigned char x;
sscanf((char *)(string + i), "%02x", &x);
printf("%02x", x);
data[i] = x;
}
printf("\n");
}
int main (int argc, const char * argv[])
{
// insert code here...
unsigned char data[64];
BytesFromHexString(data, "4d4f5cb093fc2d3d6b4120658c2d08b51b3846a39b51b663e7284478570bcef9");
return 0;
}
For
sscanfyou’d use%2xinstead of%02x. Furthermore,%2xindicates that an extraint*argument will be passed. But you’re passing anunsigned char*. And finally,sscanftakes aconst char*as first argument, so there’s no need for that cast.So give this a try :
EDIT : to clarify why this change resolves the issue : in your code,
sscanftried to writesizeof(int)bytes in a memory location (&x) that could only holdsizeof(unsigned char)bytes (ie. 1 byte). So, you were overwriting a certain amount of memory. This overwritten memory could very well have been (part of) theivariable.