Kadana Kanz
Kadana Kanz

Reputation: 197

How do I fix my memory leak?

I have

int main(void){
  while (1){
    char *input = NULL;
    char buf[1000];
    int read;
    size_t len;
    read = getline(&input, &len, stdin);

    if (-1 != read){
      sprintf(buf, "%s", input);
      lowercase(buf);; // custom function
      get_command(buf); // custom function already checked for memory leak
    }
    free(stdin);
    free(input);
    free(buf);
  }
  return 0;
}

Running this through valgrind returns:

HEAP SUMMARY
by 0x4022c2: main(prog.c:647) //  read = getline(&input, &len, stdin);

LEAK SUMMARY
still reachable: 120 bytes in 1 blocks

Since I freed everything(stdin, input, buf) why is it still giving me memory leaks? and how do I fix this?

Upvotes: 0

Views: 295

Answers (1)

M Oehm
M Oehm

Reputation: 29126

In a comment, you say that you call exit(0) from your function get_command. A call to exit(x) behaves as if the program returned x from main. That means that you skip the clean-up code at the end of main.

In order to fix this, you could return a value from get_command, for example 0 for regular operation, -1 for error or 1 for the end of input. That means that exit(0) in get_command now becomes return 1.

Your main loop could then look like:

int main(void)
{
    char *input = NULL;
    size_t len = 0;

    while (1) {
        if (getline(&input, &len, stdin) < 0) break;

        lowercase(input);
        if (get_command(input) == 1) break;
    }

    free(input);

    return 0;
}

Note that I have fixed some other issues with your code:

  • Don't use a fixed-size temporary buffer. getline can read lines of arbitrary length. If you copy these to a temporary buffer, at least make sure tat it fits; you've got the len information, after all. It is even better to use the input string directly.
  • Don't start with a NULL buffer every time you call getline. This will reduce the number of allocations, because new memory will only be allocated if a line is longer than every line read before, which shouldn't be very often. That also means that the free should go after the loop.

Upvotes: 1

Related Questions