2012-04-18 1248 views
0

最初我想將這個uint8_t數組轉換爲c中的char數組。我一直在試圖解決這個問題。我的第一個替代解決方案是將另一個類型值複製到臨時值,將tmp值複製到可寫char,然後從內存中刪除tmp值。順便說一句,這是用來伴隨blake散列函數。這裏是我的代碼片段:將uint8_t數組轉換爲c中的char數組

char * bl(char *input) 
{ 
    uint8_t output[64]; 
    char msg[]= ""; 
    char *tmp; 

    int dInt; 

    memset(output,0,64); 
    tmp = (char*) malloc(64); 
    if (!tmp){ 
      exit(1); 
    } 

    dInt = strlen(input); 

    if (dInt > 0xffff){ 
      exit(1); 
    } 
    uint8_t data[dInt]; 

    memset(data,0, dInt); 
    strlcpy(data,input,dInt); 
    uint64_t dLen =dInt; 
    blake512_hash(output, data,dLen); 

    int k; 
    for (k=0;k<64;k++){ 
      tmp[k] = output[k]; //does this "copy" is buggy code? 
    } 

    memcpy(msg, tmp,64); 
    //so here I can to delete tmp value 
    // I dont want there were left unused value in memory 
    // delete tmp; 
    free(tmp); 

    return msg; 
} 

我覺得上面的代碼仍然是效率不高,所以你有什麼意見,提示和修復? 以前非常感謝!

回答

5

首先,你永遠不應該返回一個指向局部變量的指針,因爲這個變量會在函數退出時被銷燬。您可能應該想要將輸出數組傳遞給bl函數,並使用它輸出字符串。

對於大多數情況下(如果uint8_t IS char,通常是這種情況),memcpy(msg, output, 64)應該是足夠的。如果你想嚴格要求(坦率地說,blake512_hash不應該返回uint8_t數組,如果你期望char數組作爲輸出始終),你可以簡單地在你的for循環中調用msg[k] = (char)tmp[k]並刪除memcpy

+0

我想稍後使用這個函數在Python中調用,這就是我期待這個函數稍後將返回一個字符串值。 – hafidh 2012-04-18 02:23:17

+0

@ user1309539是的,但你應該仍然解決我在我的答案中提到的問題。你根本不能將指針返回給局部變量。 – JosephH 2012-04-18 02:25:19

+0

那麼tmp變量就沒用了。從tmp變量中拷貝什麼,因爲tmp變量只是分配了char而不是輸出變量? – hafidh 2012-04-18 02:36:25

0

這裏有點不對。

dInt = strlen(input) + 1; // dInt is the size of the string including the terminating '\0'. 

strlcpy確實使用了大小而不是strlen。

msg = tmp;並沒有釋放tmp。由於msg是const char *「」(用C++術語)。

+0

恩,謝謝。再次錯誤,請給出你的建議關於上面的代碼,謝謝:) – hafidh 2012-04-18 02:26:18