第一个问题: 我在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表中。
一个问题!另外,你为什么要多次计算'token_length',然后忽略除最后一个值之外的所有值? –
第一个问题:上面的代码示例可能与您生成所描述的行为的实际代码示例不同,因为没有任何理由表示'tokens = malloc(sizeof(char)* 150);'的行为与'int token_length = 150; tokens = malloc(sizeof(char)* token_length);' –
第二个问题:阅读[null-terminated strings](https://en.wikipedia.org/wiki/Null-terminated_string) –