当我将它用于 popen 时,realloc 是否需要自由操作

问题描述

我看过一个帖子 link,其中用户回复动态分配 popen 输出

为了方便,我把代码在这里

void save_cmd(int fd) {


char buf[100];
  char *str = NULL;
  char *temp = NULL;
  unsigned int size = 1;  // start with size of 1 to make room for null terminator
  unsigned int strlength;

  FILE *ls;
  if (NULL == (ls = popen("ls","r"))) {
    perror("popen");
    exit(EXIT_FAILURE);
  }

  while (fgets(buf,sizeof(buf),ls) != NULL) {
    strlength = strlen(buf);
    temp = realloc(str,size + strlength);  // allocate room for the buf that gets appended
    if (temp == NULL) {
      // allocation error
    } else {
      str = temp;
    }
    strcpy(str + size - 1,buf);     // append buffer to str
    size += strlength; 
  }
  pclose(ls);
}

代码中他使用了 realloc 但我有两个问题。

  1. 当他使用 temp = realloc(str,size + strlength); 并在 if 分支中分配 str = temp; 时,需要使用 free 释放指针 temp?
  2. 还有str指针,在离开函数之前,需要释放吗?

我做了一个类似的功能,但差别不大

static char* exec_commands(char* command)
{
    char buf[100];
    char *temp = NULL;
    char* output = NULL;
    unsigned int size = 1;  // start with size of 1 to make room for null terminator
    unsigned int strlength;

    FILE *ls;
    if (NULL == (ls = popen(command,"r"))) {
        perror("popen");
        exit(EXIT_FAILURE);
    }

    while (fgets(buf,ls) != NULL) 
    {
        strlength = strlen(buf);
        temp = realloc(output,size + strlength);  
        if (temp == NULL) {
        // allocation error
        } else {
            output = temp;
        }
        strcpy(output + size - 1,buf);     // append buffer to str
        size += strlength; 
    }
 
    pclose(ls);
    return output;
}

int main(void) {
   char command[1000] = "ls -lh /";
   char *output = NULL;
   
   output = exec_commands(command);
   printf("%s\n",output);
   free(output);

   return 0;
}

我认为我链接的帖子有错误,你确认吗?

非常感谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)