1

我已经阅读了另一个关于使用 realloc 获取指向更大内存地址空间开头的新指针的 SO question,但我无法弄清楚我做错了什么。它打印回溯和内存转储。后来我尝试访问 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++;
  }
4

3 回答 3

4

成功后,如果需要, realloc 将释放其参数。所以删除对 free(temp) 的调用。

于 2013-01-26T18:22:26.577 回答
1

我不太清楚您要做什么,但我相信free(temp);会使strhldr无效,并且将来对它的读/写访问会给您带来麻烦。

于 2013-01-26T18:33:51.560 回答
0

第二个问题 - 未设置您的值 charctr(不是 chrctr)。这是您的循环的一个版本。我还没有测试它,但它应该很接近。

  if(c == ' ') {
      c = getchar();
  }

  int chrctr = 0;
  while(c != ' ' && c != '\n' && c != EOF){
     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");
           break;
        }
        else {
           strhldr = temp;
        }
     } 
     strhldr[chrctr] = c;
     chrctr++;
     c = getchar();
  }
  strhldr[chrctr] = 0;
于 2013-01-26T18:42:36.880 回答