【问题标题】:Why does printf("%02x"...) change output?为什么 printf("%02x"...) 会改变输出?
【发布时间】:2013-03-17 18:05:40
【问题描述】:
/*HASHING*/
unsigned char *do_hashing(unsigned char *buffer){
    unsigned char outbuffer[20];
    unsigned char output[20];
    SHA1(buffer, strlen(buffer), outbuffer);

    for (int i=0; i<20; i++) {
        output[i]=outbuffer[i];
    }

    printf("The hash: ");

    for (int i = 0; i < 20; i++) {
          printf("%02x ", outbuffer[i]);
    }

    printf("\n");

    return output;
}
/*HASHING*/

如果我删除 printf 函数,为什么这个函数会产生不同的输出(错误的输出)。例如:

./ftest
The hash: a1 2a 9c 6e 60 85 75 6c d8 cb c9 98 c9 42 76 a7 f4 8d be 73 
The hash: a1 2a 9c 6e 60 85 75 6c d8 cb c9 98 c9 42 76 a7 f4 8d be 73 
=with for-loop print

./ftest

The hash: 6c 08 40 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 00 00
=without for-loop print

在这种情况下我没有包含主函数或#includes,因为这个函数内部发生了错误。

【问题讨论】:

    标签: c hash printf sha1


    【解决方案1】:

    您正在返回一个指向局部变量 unsigned char output[20]; 的指针,

    函数结束后变量不存在导致未定义行为。

    【讨论】:

    • 更具体地说,返回指向局部变量的指针。
    【解决方案2】:

    目前,您正在返回本地指针(放置在堆栈上)。这会导致未定义的行为

    如果你想这样做,请使用malloc()函数在堆中分配内存。

    unsigned char* output = malloc(20*sizeof(unsigned char));
    

    但不要忘记调用free() 来释放分配的内存,否则会发生内存泄漏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      • 2017-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多