如何解决当我将它用于 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 但我有两个问题。
- 当他使用
temp = realloc(str,size + strlength);
并在 if 分支中分配str = temp;
时,需要使用 free 释放指针 temp? - 还有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 举报,一经查实,本站将立刻删除。