2013-03-27 88 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()來釋放分配的內存,否則你會得到內存泄漏。