2015-11-23 33 views
-3

第一個問題: 我在Redis數據庫中有一些鍵和值。我用下面的命令讀取它們:redisReply *reply = redisCommand(c, "HGETALL %s", test_id); 然後我想創建一個char數組,我想把它們放在這裏:「key = value; key2 = value2;」等 所以我想用malloc()來爲char數組分配內存。我做到以下幾點:Malloc()不工作+ char數組清除

int token_length; 
for (i = 0; i < reply->elements; i = i + 2) 
    token_length = strlen(reply->element[i]->str)+strlen(reply->element[i+1]->str)+3; 

tokens = (char*)malloc(sizeof(char)*token_length); 
memset(tokens, '\0' , sizeof(tokens)); 

for (i = 0; i < reply->elements; i = i + 2) { 
     strcat(tokens,reply->element[i]->str); 
     strcat(tokens,"="); 
     strcat(tokens,reply->element[i+1]->str); 
     strcat(tokens,"; "); 
    } 

我得到正確的數量與token_length,但如果我的malloc(...)使用它,我得到的內存錯誤,等等。相反,如果我只是把150改爲token_length的malloc(),它很好用。這是爲什麼?

第二個問題:如果我在malloc()之後沒有做memset(tokens, '\0' , sizeof(tokens)); ,我的令牌數組中有很多「垃圾」。是否應該總是在用malloc()分配後清除一個char數組?還有另一種方式,也許更好嗎?

第三個問題:當我輸出數組而不是字符「;」時,我得到\ 073,它是「;」的八進制表示。在ASCII表中。

+2

一個問題!另外,你爲什麼要多次計算'token_length',然後忽略除最後一個值之外的所有值? –

+0

第一個問題:上面的代碼示例可能與您生成所描述的行爲的實際代碼示例不同,因爲沒有任何理由表示'tokens = malloc(sizeof(char)* 150);'的行爲與'int token_length = 150; tokens = malloc(sizeof(char)* token_length);' –

+0

第二個問題:閱讀[null-terminated strings](https://en.wikipedia.org/wiki/Null-terminated_string) –

回答

0

有幾個問題 - 而不是單獨描述每一個錯誤我就發佈一個固定的版本,你可以用你原來的代碼比較一下:每題請

int token_length = 0; // <<< initialise 
for (i = 0; i < reply->elements; i = i + 2) 
    token_length += strlen(reply->element[i]->str)+strlen(reply->element[i+1]->str)+3; // <<< use += to accumulate length 

tokens = malloc(token_length + 1); // <<< need extra char for '\0' terminator 
tokens[0] = '\0';     // (also don't cast result of malloc() in C !) 

for (i = 0; i < reply->elements; i = i + 2) { 
    strcat(tokens,reply->element[i]->str); 
    strcat(tokens,"="); 
    strcat(tokens,reply->element[i+1]->str); 
    strcat(tokens,"; "); 
} 
+1

謝謝,它現在似乎工作...! – jmfel

0
int token_length=0; 
for (i = 0; i < reply->elements; i = i + 2) 
    token_length += strlen(reply->element[i]->str)+strlen(reply->element[i+1]->str)+3; 
+0

忘記+ =和初始化是如此愚蠢...謝謝 – jmfel