1

Suppose that I set a pointer in order to have a string, eg:

char *string = NULL;
size_t size = 0;
getline(&string, &size, stdin);

Is necessary to do a free(string) before end the program? As I could see in man, getline calls to malloc() and I have supposed it.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • It's not necessary, but advisable. You might want to refactor it later and code that cleans after itself is easier to place in different contexts. – Petr Skocik Nov 06 '16 at 21:27
  • 1
    I also clean up so that valgrind gives me a zero-leak report. If I have zero leaks, I don't have to worry about whether a particular leak is harmful (grows) or relatively harmless. – Petr Skocik Nov 06 '16 at 21:28

2 Answers2

4

To ensure your software doesn't have any memory leaks, yes, you should call free for any memory that you have allocated dynamically.

Memory will be reclaimed by the OS when the process terminates, and so it doesn't matter much unless you are running low on available memory. However, using free to release memory is very important if you're writing software that will run in the background, such as a daemon process.

It is recommended (almost universally) that the Right Way (tm) is to free your memory and not to rely on the OS to reclaim that space.

Greg Schmit
  • 4,275
  • 2
  • 21
  • 36
  • "In modern operating systems..." Modern or not, it's the same. C does not require programs to explicitly release memory. All C programs release their memory when they exit. – John Kugelman Nov 06 '16 at 21:29
  • Oh, I did not know that. Isn't it possible for a program written in C to request memory from the kernel (a small embedded kernel, like one that I wrote in my computer organization class) and then terminate without telling the kernel that it no longer needs the space, thus resulting in a memory leak even after the program terminates? I guess it could be called a bad kernel but it doesn't seem that it is impossible in principle. – Greg Schmit Nov 06 '16 at 21:36
  • 1
    @JohnKugelman Not universally true - operating systems such as VxWorks - a hugely commonly used RTOS was (probably still is?) single-process, multi-threaded and dynamically link-loaded programs into the system (there was little to no memory protection). Many of its competitors used a similar model. Memory leaked by a program wasn't cleaned up. It didn't violate the C standard either as there was only ever one `main()`. – marko Nov 06 '16 at 21:46
-1

It is not necessary.

There are some good reasons to, as described in another answer. But there are also some reasons not to: the code to do the freeing takes extra time to write, debug, and maintain, and is an extra potential source of bugs.

It's not possible to give a universal answer that you should or shouldn't: it's a choice that each project has to make, depending on its own circumstances.

Steve Summit
  • 45,437
  • 7
  • 70
  • 103