I'm trying to create a function that converts a hex string into an array of hex bytes. Example: str = "1c01"
-> hex_bytes = { 0x1c, 0x01 }
.
When I try to print the hex values all I get are 0s. I'm thinking it's something to do with my pointers but I am not sure. Any help would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char *input_1 = "1c0111001f010100061a024b53535009181c";
unsigned int *str_to_hexbytes(const char *hex_str) {
size_t len = strlen(hex_str);
unsigned int *hex = malloc(sizeof(unsigned int)* len / 2);
for(int i, j = 0; i < len; i = 2, j ) {
char tmp[2];
strncpy(tmp, hex_str i, 2);
hex[j] = strtol(tmp, NULL, 16);
}
return hex;
}
int main(void) {
size_t len = strlen(input_1) / 2;
unsigned int *hex = str_to_hexbytes(input_1);
for (int i = 0; i < len; i ) {
printf("%x ", hex[i]);
}
return 0;
}
CodePudding user response:
tmp
only has enough space to store the two characters you copy in. It does not have space for a null byte to terminate the string, and in fact strncpy
won't write that null byte since it didn't find one in the two characters it read.
As a result, the strtol
function reads past the end of the array, triggering undefined behavior.
Make tmp
3 characters long and add the null byte manually.
Also, you're only initializing j
, not i
, so make sure you do that as well.
for(int i = 0, j = 0; i < len; i = 2, j ) {
char tmp[3];
strncpy(tmp, hex_str i, 2);
tmp[2]=0;
hex[j] = strtol(tmp, NULL, 16);
}
CodePudding user response:
You are not initializing i with 0. That might be your problem. int i, j = 0;
only changes j's value to zero, i remains garbage since it is allocated from stack.
Also a few suggestions:
- Since you are using string's length in main too, you can only calculate it in main and send it to the function.
- You used a 'malloc' which requires you to call 'free' also. After you are done using the pointer call
free(hex)
- Iterate until
len - 1
since you are using one memory block ahead in your for loop's body.