2017-04-26 63 views
0

我有一個程序來通過用戶輸入,發送該用戶輸入作爲一個參數傳遞給函數,這使得計算,則該字符數組返回到主()函數將要輸出那裏。返回char數組失敗,且不printf()的

return (char *)&buf;運行一個printf()語句時工作正常。 然而,當沒有printf(),回報似乎並沒有工作,因爲main()功能無法輸出返回值。

下面的代碼:

#include <stdio.h> 
#include <string.h> 
#include <openssl/sha.h> 

using namespace std; 

char* hash_function(char* input_string) 
{ 
    int i = 0; 
    unsigned char temp[SHA_DIGEST_LENGTH]; //where we will store the SHA digest. length = 20 
    char buf[SHA_DIGEST_LENGTH*2]; 

    memset(temp, 0x0, SHA_DIGEST_LENGTH); //array of size 20 to store SHA1 digest 
    memset(buf, 0x0, SHA_DIGEST_LENGTH*2); //array of size 2*20 to store hex result? 

    SHA1((unsigned char *)input_string, strlen(input_string), temp); 

    for(i=0; i<SHA_DIGEST_LENGTH; i++){ 
     sprintf((char*)&(buf[i*2]), "%02x", temp[i]); 
     //element in temp[i] formatted with %02x and stored in buf[i*2] 
    } 

    //printf("In FUNCTION: %s\n", buf); //************************************* 
    return (char *)&buf; 
} 

int main(int argc, char * argv[]) 
{ 
    if(argc != 2) 
    { 
     printf("Usage: %s <string>\n", argv[0]); 
     return -1; 
    } 

    char *hash = hash_function(argv[1]); 

    printf("Plaintext:\t%s\nSHA-1:\t\t%s\n\n", argv[1], hash); 

    //FILE *file = fopen("temp_file.txt", "a+"); //open file to write to 
    //fprintf(file, "Plaintext: %s\nSHA-1: %s\n\n", argv[1], buf); 

    return 0; 
} 

我已經用星號標記的線是print()線我指的是。

爲了編譯,使用g++ [file_name] -lcrypto -o [output] 您可能需要下載的OpenSSL/sha.h包。

+1

'使用命名空間std;'是不是C. –

+3

'buf'成爲功能之外無效。 – BLUEPIXY

+0

請不要期望評論者「下載openssl/sha.h包」。 –

回答

0

你是返回一個指針在棧上分配的緩衝區。一旦hash_buffer返回,分配給buf的內存就會消失。你需要用malloc在堆上分配一個buf。因此,改變你的函數:

char* hash_function(char* input_string) 
{ 
    int i = 0; 
    unsigned char temp[SHA_DIGEST_LENGTH]; //where we will store the SHA digest. length = 20 
    char *buf = NULL; 
    buf = malloc(SHA_DIGEST_LENGTH*2); 
    if (buf == NULL) { 
     return NULL; 
    } 

    memset(temp, 0x0, SHA_DIGEST_LENGTH); //array of size 20 to store SHA1 digest 
    memset(buf, 0x0, SHA_DIGEST_LENGTH*2); //array of size 2*20 to store hex result? 

    SHA1((unsigned char *)input_string, strlen(input_string), temp); 

    for(i=0; i<SHA_DIGEST_LENGTH; i++){ 
     sprintf((char*)&(buf[i*2]), "%02x", temp[i]); 
     //element in temp[i] formatted with %02x and stored in buf[i*2] 
    } 
    return buf; 
} 
+0

我讀到另一個線程這表明這一點,但海報。被告知,這是不好的做法,因爲它不清楚誰應該被允許釋放這個記憶,那個保留的或另一個記憶呢?我會和它一起去的,我只是希望找到一個更「正確」的方式去解決它。 – Tawm

+1

這是在功能分配內存,並期望調用程序釋放它可以接受的做法。 – bruceg

+0

爲了提高穩健性,你可以通過初始化'temp',並使用'calloc'用於替代memset的調用'buf' –

相關問題