简体   繁体   English

无法 function 的 printf output 返回 Z0D61F8370D1412F80B4 中的数组指针

[英]not able to printf output of a function returning an array pointer in C

I'm trying to create a function that converts a hex string into an array of hex bytes.我正在尝试创建一个将十六进制字符串转换为十六进制字节数组的 function。 Example: str = "1c01" -> hex_bytes = { 0x1c, 0x01 } .示例: str = "1c01" -> hex_bytes = { 0x1c, 0x01 }

When I try to print the hex values all I get are 0s.当我尝试打印十六进制值时,我得到的都是 0。 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;
}

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. tmp只有足够的空间来存储您复制的两个字符。它没有空间用于 null 字节来终止字符串,实际上strncpy不会写入 null 字节,因为它在两个字符中找不到一个它读了。

As a result, the strtol function reads past the end of the array, triggering undefined behavior .结果, strtol function 读取到数组的末尾,触发未定义的行为

Make tmp 3 characters long and add the null byte manually.使tmp长 3 个字符并手动添加 null 字节。

Also, you're only initializing j , not i , so make sure you do that as well.此外,您只是在初始化j ,而不是i ,因此请确保您也这样做。

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);
}

You are not initializing i with 0. That might be your problem.您没有用 0 初始化 i。这可能是您的问题。 int i, j = 0; only changes j's value to zero, i remains garbage since it is allocated from stack.仅将 j 的值更改为零,i 仍然是垃圾,因为它是从堆栈分配的。

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.由于您也在 main 中使用字符串的长度,您只能在 main 中计算它并将其发送到 function。
  • You used a 'malloc' which requires you to call 'free' also.你使用了一个'malloc',它要求你也调用'free'。 After you are done using the pointer call free(hex)使用指针调用free(hex)完成后
  • Iterate until len - 1 since you are using one memory block ahead in your for loop's body.迭代直到len - 1因为您在 for 循环的主体中使用了一个 memory 块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM