title: Is it really important to free allocated memory if the program's just about to exit?
body: <p>I understand that if you're allocating memory to store something temporarily, say in response to a user action, and by the time the code gets to that point again you don't need the memory anymore, you should free the memory so it doesn't cause a leak. In case that wasn't clear, here's an example of when I <em>know</em> it's important to free memory:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  void countToNumber(int n)
  {
      int *numbers = malloc(sizeof(int) * n);
  
      int i;
      for (i=0; i&lt;n; i++) {
          numbers[i] = i+1;
      }
      for (i=0; i&lt;n; i++) {
          // Yes, simply using "i+1" instead of "numbers[i]" in the printf would make the array unnecessary.
          // But the point of the example is using malloc/free, so pretend it makes sense to use one here.
          printf("%d ", numbers[i]);
      }
      putchar('\n');
  
      free(numbers); // Freeing is absolutely necessary here; this function could be called any number of times.
  }
  
  int main(int argc, char *argv[])
  {
      puts("Enter a number to count to that number.");
      puts("Entering zero or a negative number will quit the program.");
  
      int n;
      while (scanf("%d", &amp;n), n &gt; 0) {
          countToNumber(n);
      }
  
      return 0;
  }
  </code></pre>
  
  <p>Sometimes, however, I'll need that memory for the whole time the program is running, and even if I end up allocating more for the same purpose, the data stored in the previously-allocated memory is still being used. So the only time I'd end up needing to free the memory is just before the program exits.</p>
  
  <p>But if I don't end up freeing the memory, would that really cause a memory leak? I'd think the operating system would reclaim the memory as soon as the process exits. And even if it doesn't cause a memory leak, is there another reason it's important to free the memory, provided this isn't C++ and there isn't a destructor that needs to be called?</p>
  
  <p>For example, is there any need for the <code>free</code> call in the below example?</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(int argc, char *argv[])
  {
      void *ptr = malloc(1024);
      // do something with ptr
      free(ptr);
      return 0;
  }
  </code></pre>
  
  <p>In that case the <code>free</code> isn't really inconvenient, but in cases where I'm dynamically allocating memory for structures that contain pointers to <em>other</em> dynamically-allocated data, it would be nice to know I don't need to set up a loop to do it. Especially if the pointer in the struct is to an object with the same struct, and I'd need to recursively delete them.</p>