2013-03-27 91 views
0
/*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函数,为什么这个函数产生不同的输出(错误的)。例如:为什么printf(“%02x”...)更改输出?

./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 

因为这个函数内发生错误我还没有包括在此情况下,主功能或#包括。

回答

7

你是返回一个指向一个局部变量unsigned char output[20];

函数结束造成不确定behavor后的变量不存在。

+1

更具体地说,返回一个指向**局部变量的指针。 – 2013-03-27 15:24:23

1

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

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

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

但是不要忘了拨free()来释放分配的内存,否则你会得到内存泄漏。