Your code is erroneous for multiple counts and the casts hide the problems:
Casting the return value of malloc
is not necessary in C and can potentially hide an unsafe conversion if you forget to include <stdlib.h>
:
in = (unsigned char *)malloc(16);
Casting the return value of strlen
to (size_t)
is useless, even redundant as strlen
is defined to return a size_t
. Again you might have forgotten to include <string.h>
...
for (size_t i = 0; i < (size_t)strlen(argv[2]) / 2; i += 2) {
long tmp = 0;
strtol
takes a const pointer to char
, which argv[2] + i
will convert to implicitly. The cast (const char*)
is useless. The second argument is the address of a char*
. You pass the address of the fifth element of argv
, in other terms &argv[4]
, most certainly not what you indent to do, although your loop's purpose is quite obscure...
tmp = strtol((const char *)argv[2] + i, &argv[2] + 2, 16);
Copying the long value in tmp
with memcpy
would require to copy sizeof(tmp)
bytes. Copying the first byte only has an implementation defined effect, depending on the size of char
and the endianness of the target system:
memcpy(&in[i], &tmp, 1);
}
You should post a complete compilable example that illustrates your problem, a code fragment is missing important context information, such as what header files are included, how variables are defined and what code is executed before the fragment.
As written, your code does not make much sense, trying to interpret its behavior is pointless.
Regarding the question in reference, your code does not even remotely provide a solution for converting a string of hexadecimal characters to an array of bytes.