【问题标题】:Malloc() doesn't work + char array clear [closed]Malloc()不起作用+ char数组清除[关闭]
【发布时间】:2015-11-23 15:32:21
【问题描述】:

第一个问题: 我在 Redis 数据库中有一些键和值。我使用以下命令阅读它们:redisReply *reply = redisCommand(c, "HGETALL %s", test_id); 然后我想创建一个 char 数组,我想把它们放在这样的地方:“key=value;key2=value2;”等等 所以我试图使用 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(...) 中使用它,我会遇到内存错误等。相反,如果我只是在 malloc() 中放入 150 而不是 token_length,它会很好用。这是为什么呢?

第二个问题:如果我不做memset(tokens, '\0' , sizeof(tokens));malloc() 之后,我的令牌数组中有很多“垃圾”。是否应该在使用malloc() 分配后始终清除 char 数组?还有其他更好的方法吗?

第三个问题:当我输出数组而不是字符“;”时,我得到\073,它是“;”的八进制表示在 ASCII 表中。

【问题讨论】:

  • 每个问题一个问题!另外,你为什么要多次计算token_length,然后忽略除最后一个值之外的所有值?
  • 第一个问题:您上面的代码示例可能与产生您描述的行为的实际代码示例不同,因为没有理由tokens = malloc(sizeof(char)*150); 的行为与int token_length = 150; tokens = malloc(sizeof(char)*token_length); 不同
  • 1) 不要在 C 中转换 malloc 和朋友的结果。2) sizeof(char) 永远不会返回与 1 不同的任何东西,所以它是无用的。
  • token_length = --> token_length +=
  • 。您永远不需要乘以 sizeof(char),因为 sizeof(char) 根据定义为 1

标签: c arrays malloc


【解决方案1】:

有一些问题 - 我不会单独描述每个错误,我只会发布一个修复版本,您可以将其与您的原始代码进行比较:

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,"; ");
}

【讨论】:

  • 谢谢,现在好像可以用了……!
【解决方案2】:
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;

【讨论】:

  • 忘记了 += 并且初始化太愚蠢了......谢谢
猜你喜欢
  • 1970-01-01
  • 2018-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-12
  • 2013-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多