Sergio
Sergio

Reputation: 275

Free malloc when its value is returned by a function

I have the following function:

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;
}

Related part in main:

 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; 
    }

It returns a string to the main function, problem is I use malloc() to allocate memory for this function, if I use free(stringts) before return then obviously nothing will get returned, so how I my supposed to use free() while still returning it?

Note:

I found this link here: How do I free() after malloc() when the result of malloc() is returned by the function?

It is not in the same programming language hence why I am asking again.

Upvotes: 0

Views: 62

Answers (1)

Marc Balmer
Marc Balmer

Reputation: 1830

If you want to return it, you must not free() stringts. You must later free() it in the calling function.

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; 
    }

Upvotes: 2

Related Questions