c - C中使用realloc的动态内存分配

标签 c memory dynamic allocation

我已经阅读了关于使用 realloc 获取指向更大内存地址空间开头的新指针的其他 SO 问题,但我无法弄清楚我做错了什么。它打印回溯和内存转储。稍后我尝试访问 strhldr,但我认为它甚至无法访问那么远。

char *strhldr = (char *)malloc(strsize);

 int chrctr = 0;
 if(chrctr == strsize - 3){ // when you get close
  strsize = strsize*2; //double size
  char *temp = realloc(strhldr, strsize); //make more room
    if(temp == NULL)
     printf("reallocate failed\n");
    else{
     strhldr = temp;
     free(temp); // removed same issue
    }
} 

// Later attempt to add it to an array
cmdargs[i] =  strhldr;

这一切都在一个 while 循环中,其中 chrctr 和 strsize 递增

完整代码

  int argctr = 64;
  char **cmdargs = (char **) malloc(argctr * sizeof(char*));
  char c = getchar();
  int i = 0;


  while(c != '\n' && c != EOF){ //read through a String of stdin
  int strsize = 32;
  char *strhldr = (char *)malloc(strsize);
  char *strstarthldr = strhldr;


    if(c == ' ')
      c = getchar();
    while(c != ' ' && c != '\n' && c != EOF){

      int chrctr = 0;
     if(chrctr == strsize - 3){ // when you get close
      strsize = strsize*2; //double size
      char *temp = realloc(strhldr, strsize); //make more room
        if(temp == NULL)
         printf("reallocate failed\n");
        else
         strhldr = temp;

    }      //add that word to the array of strings
      strhldr[chrctr] = c;
      chrctr++;
      c = getchar();

    }
    strhldr[charctr] = '\0';
    //strhldr = strstarthldr;
    cmdargs[i] =  strhldr;
    i++;
  }

最佳答案

成功时,realloc 将在需要时释放它的参数。所以删除对 free(temp) 的调用。

关于c - C中使用realloc的动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14540044/

相关文章:

c - 在 C 中是一个查找表,替代 bash||php 中的变量

c - 使用 C 的 Hadoop 流式处理

c++ - 急切加载整个模型以估计 Tensorflow Serving 的内存消耗

python - 在 re.sub 中使用变量,用于 Python 解析多个日期时间格式的字符串?

c# - 在 Scala 中实现 ExpandoObject

c - 由于内存对齐不正确,使用 SSE 内部函数时出现段错误

正割法求多项式根的C程序

r - 不同大小矩阵的相同内存使用

memory - 为什么哈希表比其他数据结构占用更多内存?

Javafx 网格 Pane ..无法动态添加行..而不收缩