Proper Way to Free Memory of a Returned Variable

w m picture w m · Apr 15, 2015 · Viewed 19k times · Source

I created a function designed to get user input. It requires that memory be allocated to the variable holding the user input; however, that variable is returned at the end of the function. What is the proper method to free the allocated memory/return the value of the variable?

Here is the code:

char *input = malloc(MAX_SIZE*sizeof(char*));
int i = 0;
char c;

while((c = getchar()) != '\n' && c != EOF) {
    input[i++] = c;
}

return input;

Should I return the address of input and free it after it is used?

Curious as to the most proper method to free the input variable.

Answer

Iharob Al Asimi picture Iharob Al Asimi · Apr 15, 2015

It's quite simple, as long as you pass to free() the same pointer returned by malloc() it's fine.

For example

char *readInput(size_t size)
 {
    char *input;
    int   chr;
    input = malloc(size + 1);
    if (input == NULL)
        return NULL;
    while ((i < size) && ((chr = getchar()) != '\n') && (chr != EOF))
        input[i++] = chr;
    input[size] = '\0'; /* nul terminate the array, so it can be a string */
    return input;
 }

 int main(void)
  {
     char *input;
     input = readInput(100);
     if (input == NULL)
         return -1;
     printf("input: %s\n", input);
     /* now you can free it */
     free(input);
     return 0;
  }

What you should never do is something like

free(input + n);

because input + n is not the pointer return by malloc().

But your code, has other issues you should take care of

  1. You are allocating space for MAX_SIZE chars so you should multiply by sizeof(char) which is 1, instead of sizeof(char *) which would allocate MAX_SIZE pointers, and also you could make MAX_SIZE a function parameter instead, because if you are allocating a fixed buffer, you could define an array in main() with size MAX_SIZE like char input[MAX_SIZE], and pass it to readInput() as a parameter, thus avoiding malloc() and free().

  2. You are allocating that much space but you don't prevent overflow in your while loop, you should verify that i < MAX_SIZE.