Question

Many libraries like SDL, etc, etc have in their tutorials method calls that free resources right before quitting the program, but as far as I know, most OSes free all memory from the processes when they quit, why do I need to bother to free them if the application is going to quit anyway?

Était-ce utile?

La solution

Even if your OS (not all do that) frees memory at exit, there are some reasons:

  • it's good manner
  • it adds symmetry, so code looks better
  • OS does not automatically free some resources at exit, like devices (sensors, scanners...)
  • if someone takes this code and places it in a program that uses the libraries only in a small part of his runtime, the resources will be free when not needed.
  • if you are looking for bad memory leaks, your debugger won't find these unimportant ones.

Autres conseils

Memory and resources are not the same thing.

Memory is released automatically.

Resources may, or may not, be released automatically.

Whether the resources allocated to a program will be reclaimed or not depends on the Operating systems. Note that specifically some embedded systems do not free the resources.

Most operating systems do reclaim and free the resources allotted but it is bad practice to rely on the behavior of the OS for this and hence you should free all the acquired resources before you quit your program.

In general I agree what others have said: if you don't practice good habits in the little things, you'll fail with the big ones as well. However your question rang (an old) bell, about crash-only software.

While that concept extends "a little" further than your original question (it not only deals with OS resources, but with your own (open files, etc.), you might still be interested in it.

The basic idea is, if software should not destroy user data, etc. in the face of a crash (think of databases / tx logs, etc.) why should you even design/program a clean exit path. If you need to restart, rerun it, you might as well "let it crash".

Well, I guess one can argue about the virtues of that all day, but it is interesting nevertheless.

It is a good idea to tidy up after yourself.

For one - freeing up resources will tidy up file descriptors/network connections/shared memory etc. in a controlled manner.

Secondly, if you are using something like purity you can ensure that all the memory is taken into account of - thus giving a better sense that no memory leaks are occurring.

I suppose the first thing that should be mentioned is that not all resources are the same.

None of these structures (in most OSes) are automatically cleaned up at application close:

  • Shared memory pools
  • Named Win32 Mutex/Semaphore/Event/etc. objects
  • Certain kinds of socket connections
  • Proprietary hardware device driver data structures (obscure)

... and I'm sure I'm forgetting some.

In the small, it might be easy to know whether your application uses any of these types of objects and control for it. However, in larger applications it isn't hard to get to a point where you have some deeply-embedded (3rd party?) subsystem that does allocate one or more of these special structures and if the rest of your application leaks like a sieve, you might be in trouble.

It is really a matter of engineering discipline that says your application should clean up after itself on exit. You may not need it now but you might appreciate it later as your application gets larger.

One reason I see is:

Assume that you have the memory leaks dumped in the output window of your development environment on application exit. If you do not "clean-up" in a proper way you will have problems detecting the true leaks from all the leaks that come from "not bothering with it"

Well it is mostly true that today almost all mainstream operating systems do indeed free all (or most) resources a program has allocated upon its termination. However, this is firstly not true for all resources (e.g. on my mac open sockets stay open for a while when not closed properly at program termination) and secondly I believe not for all operating systems.

Historically, OSses did not bother at all (esp. some of the older 16bit OSses) so cleaning up all your resources upon programming termination has become and still is good programming practice and a programmer not cleaning up his stuff is generally considered a bad programmer.

First of all: not all resources are freed by the OS when process ends, for example:

  1. Files - sometimes you may what to remove files you had opened.
  2. Named resources: named mutexes, shared memory etc. etc.
  3. More complex application level states settings, statistics and much more.

So once you manage all resources in same way you are doing the right thing.

You are correct, most modern operating systems will release memory, file handles, etc. for you when the application exits. So I would fully agree with you and not bother releasing any resources if resources available to applications were unlimited.

The fact is, resources are not unlimited, it's actually quite the opposite, so anything you take is something another application running on the system cannot have. In many cases you will need a resource not throughout the life of your app, but only for some portion of it, so you want to play nice with the rest of the system and only take what you need while you need it.

The practice of not releasing resources is very common in embedded devices, since for these the application is the only thing running, and it doesn't even get to exit, the only way out is to turn off the device. I work with one such systems, and while the embedded device has no issues from not releasing stuff, we engineers suffer from it for several reasons:

  • when testing the embedded application on a regular PC we are forced to model the simulated device as a process that starts and ends. If resources were released properly we could have a single process run several tests in the same run, including tests that start and stop the simulated device.
  • at some point we had to work on a project that required us to take part of the embedded code and publish it as a dynamic link library for Windows/Linux that performs a subset of the functions of the real device, but without the actual device. Because of the resource problem, users cannot load and unload this DLL multiple times into their applications, because each time they do that a decent chunk of memory is taken and never released back. We have documented it as a limitation, we ask our users to link the library to the application instead of loading it dynamically. Unfortunately after 10+ years that this embedded device has been in development it would be very complicated to locate and fix all these resource allocations, so we keep putting it off and have a sub-optimal product instead.
  • when we use static and dynamic code analysis tools to locate real defects we get a ton of false positives, so many that we had to develop tools that filter those out to not risk missing the real ones in all the noise.

My advice is that you write the code as if the OS won't help you, as that is what will give you the most choices to improve the software in the future.

These are good manners.

And you never know if you want to turn your program into something persistently running over and over again in the future.

That said, it is not mandatory and as always you can break the rules if you know what you're doing.

The operating system tries to free all resources still held by a process after it closes as a last ditch effort to keep the system running. Applications are supposed to clean up after themselves, but the OS's auto-cleanup is designed to stop badly written programs taking down the whole system by memory leaks, held files etc. So you really should not rely on it as the default mode for your application to be shut down! Ideally, the OS will never have to clean up after a process has shut down, because all programs should be well-written to clean up after themselves. However, in practice, some software has mistakes or is simply poorly written and it is a useful feature for the OS to clean up after these lazy programs.

Also, the OS will not clean up some resources anyway. If you write a file to disk and intend to remove it on shut-down, the OS will not delete that file automatically (what if it was the user's document?). But if you don't clean it up yourself, your program has permanently "leaked" disk space. There are many other examples for other types of resources other than files.

So don't write bad software which assumes the OS will clean up: it probably won't do it 100%, and that mechanism is only for crappy software. Write good software instead!

The sense of releasing the memory even for objects whose lifetime corresponds to that of an application is immediately obvious once you try to find a memory leak with Valgrind or something, because your output wil be flooded with reports on those objects. After all, a leak is still a leak.

It is not required to free memory when the application quits. The OS takes care of reclaiming the memory. As others mentioned, resources like printer, files require to free their locks for allowing other programs to access them.

Say if your code does not free any memory (even when it runs) and when your code/project size increases, it will eat all of your system memory and maintenance becomes hard to fix them. So for all future purposes, it is a good practice to free memory.

As you know, depending on the OS, memory is usually (hopefully it is!) release automagically when the process exits.

However, many libraries, like SDL, ask the OS to allocate system resources that do not get freed in a timely fasion (maybe not even untill shutdown) unless explicitly freed by the application.

Besides being nice to the operating system and cleaning up for it, freeing any memory you allocate is important in any application that runs for an unknown amount of time because that memory takes up space that other applications might need.

It's also a good habit to clean up after yourself. :)

As the other answers point out, there is a difference between resources and memory. I can speak only in context of the Win32 api, but I'm sure that similar concepts are applicable for libraries like SDL. Some libraries may provide for automatic release of resources, some may not. It is always good practice to free up your resources irregardless. Device specific resources are an example of resources that may cause problems if they are not freed. You might want to check with the documentation of your library for details about resource management.

I know I am late to the party, but please free all your memory and resources, if for no other reason than because when you end up getting a real memory leak, like on inside a loop, then the last thing I need is your garbage cluttering up my memory profilers output like valgrind.

Secondly cleaning up memory isn't a problem use smart pointers the do all the work for you with little to no overhead.

Finally, this is even more inexcusable if it a library, I don't care if it is not a continuous leak (ie 1 off garbage - eg: creation of a singleton) a library should not leave data on the freestore.

Whenever any new process starts some memory is allocated to it. The memory can be of four types as:

 1.Heap
 2.Local
 3.Virtual
 4.Global

Local generally used for the main() variable's addresses because these main variables will be used frequently. Global keeps the record of global variables. Heap memory is allocated (pages are allocated) to programs or process and it have the information of program's data and functions.

What actually happens that OS uses the concept of pointers. And whenever in program one pointer start pointing to some other memory(due to some code error) and stop pointing to previous memory location then the last memory space is still in use in heap memory. but this memory space is of no use. When any program exits it releases the memory according to its variables and functions location. But as i told the un-pointed memory have still data but no one is pointing to it so program can not release it.

To release that unused memory location we use free(). As malloc, realloc, calloc, free all are the functions of heap memory. When we call free it delete the pages that were allocated for the program and it also releases that unused memory too.

  In simple words,

50-100 memory location allocated to your program. a and b(variables in your program) are pointing to 60 and 70. due to some code error , b starts pointing to 60. So now a and b both pointing to 60. No one pointing to 70 now. When program will start exit it will get the memory location of a and release it .Then it will get the memory location of b and release it .But program will never come to know the location of 70 because no one is pointing it.So it wont release the memory of 70.

Whereas when u call free() it directly release the whole page and with that whole 50-100 memory location will be release. Now both un-pointed and pointed memory locations are free for use.

Now a days the languages have garbage collector to do the function of the free(). But if we talk about the OSes then they have to do it itself so in libraries always free is used. And it is also best way of writing code.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top