c - 函数返回值时释放 malloc
问题描述
我有以下功能:
char *lsl(){
chdir("/Users/some/directory");
FILE *fp;
if ((fp = popen("ls -l", "r")) == NULL) {
perror("popen failed");
return (char *)EXIT_FAILURE;
}
size_t str_size = 1024;
char *stringts = malloc(str_size);
if (!stringts) {
perror("stringts allocation failed");
return (char *)EXIT_FAILURE;
}
stringts[0] = '\0';
char buf[128];
size_t n;
while ((n = fread(buf, 1, sizeof(buf) - 1, fp)) > 0) {
buf[n] = '\0';
size_t capacity = str_size - strlen(stringts) - 1;
while (n > capacity) {
str_size *= 2;
stringts = realloc(stringts, str_size);
if (!stringts) {
perror("stringts realloation failed");
return (char *)EXIT_FAILURE;
}
capacity = str_size - strlen(stringts) - 1;
}
strcat(stringts, buf);
}
if (pclose(fp) != 0) {
perror("pclose failed");
return (char *)EXIT_FAILURE;
}
return stringts;
}
主要相关部分:
char *out=lsl();
if(send(new_socket, out, 200, 0)<0){. //sending the string to the client to print it there
printf("Error in send! %s\n", strerror(errno));
return -1;
}
它向主函数返回一个字符串,问题是我用来malloc()
为这个函数分配内存,如果我在此free(stringts)
之前使用return
显然不会返回任何内容,那么我应该如何free()
在返回它的同时使用它?
笔记:
我在这里找到了这个链接:当函数返回 malloc() 的结果时,如何在 malloc() 之后释放()?
它不是同一种编程语言,因此我为什么要再次询问。
解决方案
如果你想返回它,你一定不能 free() 字符串。您必须稍后在调用函数中释放()它。
char *out=lsl();
int r = send(new_socket, out, 200, 0);
free(out);
if(r <0){. //sending the string to the client to print it there
printf("Error in send! %s\n", strerror(errno));
return -1;
}
推荐阅读
- python - 如何在数据库查询中替换 NULL?
- vue.js - 为什么 vue.js 为小图像渲染 base64 图像
- python - 替换字典列表中的一个字符并将对象返回到原始格式
- java - G1GC Old Gen 提交的堆不断增长,使用是恒定的 - 导致 Eden 饥饿
- json - 无法使用 utf8 编码上下文
- apache-kafka - 为什么 apache kafka 不使用标准的 java doc?
- javascript - 在 Javascript 中指定变量类型(用于解析目的)
- c# - 如何仅在部分布局上使用 WPF DataTemplates
- python-3.6 - 使用 Perforce 在 p4python 中复制命令
- scheme - 添加括号更改条件评估