2015-11-23 32 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