首页 > 解决方案 > 函数返回值时释放 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() 之后释放()?

它不是同一种编程语言,因此我为什么要再次询问。

标签: cmalloc

解决方案


如果你想返回它,你一定不能 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; 
    }

推荐阅读