At one point of time, I have to terminate my application developed in Delphi XE2 using Application.Terminate.
I would like to confirm, will there be any memory loss due to this?
If yes, what all possible scenarios I need to take care of?
And how to tackle them?
Calling the Application.Terminate method doesn't produce memory leaks this method is equivalent to call the PostQuitMessage function. The memory leaks are caused when the resources are not released properly. To check if you have memory leaks in your app you can set the global variable ReportMemoryLeaksOnShutdown to true.
No matter how you close a process, no memory will be leaked. When a process closes, the OS reclaims all the memory owned by the process.
Now, Application.Terminate results in an orderly shutdown, starting at the Application object. All objects owned by Application will be destroyed. If those objects in turn own other objects, the owned objects will be destroyed. However, in terms of leaking memory it is not possible for a process to terminate and leak memory. It is possible for a process to terminate and leave certain resources in an ill-defined state which is why it is often advisable to terminate a process in an orderly fashion.
Related
I am trying to debug memory usage in a large application using Delphi 7. I was able to installed fastmm debug full dll and with it solve some leak problems.
I also installed the memory usage tracker, allowing me to see which blocks were allocated and of what size they are.
My question is, is there a way to find out where the blocks were allocated? I know it is possible because if the memory wasn't freed a stack trace gets printed. Is there a way to 'poke' at fastmm to get it to print the stack trace for a given allocation?
Side question: if the start address of an allocation is known, is there a way to find out which class the object is? (assuming that the allocation was for a object.
You can either:
try to use LogAllocatedBlocksToFile procedure. If its ALastAllocationGroupToLog param is less than AFirstAllocationGroupToLog or is zero, then all blocks along with their allocation call stacks are logged. However, if your app has many memory allocations, prepare to long waiting. I experienced about 4 hrs wait time and 1.5Gb resulting file. (Side-note: use glogg to view such large files)
modify FastMM4.pas so implementation's LogCallStack will be visible in interface. Or you can try to use it directly from FastMM_FullDebugMode.dll
On the side question: try to use DetectClassInstance function.
If you use FullDebugMode and enable the conditionals that will write the data to a file, then you should get exactly what you're asking for. It will write out a stack trace for every leaked allocation when the program shuts down. (If you're debugging a program with a lot of memory leaks, this can take a while. I've seem it make shutdowns last for 10 minutes or more if the leaking item is a container that holds lots of other objects.)
Considering you said in a comment that the app's memory gets cleaned up nicely on app's closing for me sounds you're looking for logical memory leaks - in other words: objects that are alive more time than needed but when the time arrive for finish the app they are cleaned because exist code to clean them.
Example:
Create an TForm using the Application as owner and the variable that references it is the global one that Delphi creates when create the form's unit.
Config the Form's CloseAction to caHide (in the OnClose event)
Show the form, operate on it
Close the form and never more use it until the app closes
Close the app, which makes Application clear all the objects it owns
So you have an logical memory leak but not an physical memory leak - which is the kind that FastMM can easily detect. Since you not intended that our hypothetical TForm live until the application finish, it semantically leaked but since it is referenced and there is code that destroys it at the end of application, to FastMM is a normal allocation.
That said appears you need not the memory dump of the memory manager, but an memory profiler.
I would like to know WHY do we use "Finalization" if we want to destroy something when closing the application? doesn't closing the application frees all objects directly without calling .Free?
Thanks.
Doesn't closing the application frees all objects directly without calling Free?
No. Delphi class instances are not garbage collected and so they need to be manually destroyed.
However, if you are talking about an executable process, then it can be perfectly acceptable not to dispose of certain objects since the operating system will re-claim all resources owned by a process when that process terminates. So even though Delphi destructors don't run, the OS tidies everything up when a process terminates. It is not possible for a process to leak any system resources once it has terminated.
Note that if the unit is included in a DLL or a package then failure to destroy all objects at finalization time will lead to memory leaks, if that DLL is repeatedly loaded and unloaded into a single process.
If you know that your code only ever runs in an executable, then feel at liberty not to Free objects at finalization time. Be aware that if you are using a memory leak detection tool then doing so will result in your intentionally leaked object being treated as a memory leak. Deal with that by calling RegisterExpectedMemoryLeak.
One final point to make is that an object's destructor sometimes does more than free memory. Sometimes it can save values to a settings file, or the registry, for example. Naturally you would not want to omit running the destructor for such an object.
Adding to the final point of David Hefferman's answer: There are other resources that might need to be freed correctly, like file handlers that generate a checksum or some hardware connected to the PC that must be put in a specific state (e.g. a laser to be turned off, which is what I am currently working with).
Writing a program for the iphone. Realized that I forgot to release an object, but there was really no indication that the object was not released everything just worked.
What is the best way to track something like this down? Is there a way to see what objects still exist in memory when the program exits out?
Take a look at the Leaks tool in Instruments.
Strictly speaking, when the program exits, it doesn’t matter what you’ve left in memory: the system frees everything that your application allocated throughout its lifetime. Since iOS 4, though, apps usually just get frozen in the background and don’t exit until the system kills them to free up memory. To avoid that—and to reduce your app’s memory footprint, which is important while it’s running—you should, as highlycaffeinated and Daniel suggested, use Instruments’s Leaks tool to check for objects that aren’t getting deallocated properly.
When the app exits, anything in memory is destroyed by the system (not deallocated-- but just outright destroyed when the address space is given back to the system).
While others have suggested using the Leaks tool to find leaks in your app, Leaks won't find many many kinds of memory accretion. If an object is allocated, shoved in a cache somewhere, then the key to that object in the cache is lost, the object is effectively leaked (can never be used again) but won't be find by Leaks because it is still connected to your viable object graph.
A better bet is to use Heapshot analysis to see how your app's object graph grows over time. I wrote up a tutorial on using Heapshot analysis that you might find useful.
If you want to grab a snapshot just before your app exits, then put a sleep(1000); into your code in either an application termination handler or somewhere else that is executed just before the app exits.
Just remember to remove it before shipping a production build. :)
Once an application quits - you don't have access to that. But Instruments (an XCode tool) can look for memory leaks.
Nothing exists in memory when pprogram exits. But you can start with analyzing your code (Product -> Analyze) and running it with (Product -> Profile) Allocations or Leaks in Instruments to find memory management issues.
I have multithreaded application and I've got a little problem when application ends: I can correctly terminate the thread by calling TThread.Terminate method in Form1.OnDestroy event handler, but the termination does take some time and so I can't free the memory (by TThread.Free method).
Unfortunately for some other reason I must have TThread.FreeOnTerminate property set to false, so the thread object isn't destroyed automatically after thread termination.
My question is probably a little silly and I should have known it a long time ago, but is this ok and the thread will be destroyed automatically (since the application just ends), or is it a problem and the memory would be "lost"? Thanks a lot for explanation.
You should wait for the thread to terminate before you begin the process off shutting down the rest of your application, otherwise shared resources may be freed under the threads feet, possibly leading to a string of access violations. After you have waited for thread termination, then you can free it. In fact, that's what the TThread destructor does for you.
If there are no shared resources, then sure, let it die by itself. Even if the thread terminates after the main thread, all that is required is that all your threads exit for the program to terminate. Any memory associated with the thread's object will just get cleaned up and given back to the OS with everything else.
BUT, be careful! If your thread is taking a while to exit, it can lead to a zombie process sitting there churning away without a GUI. That is why it is very important to check the Terminated flag very often in the thread loop, and exit the thread.
N#
Your question is not silly or simple - read the MSDN article. All in all, if you want to be on the safe side you are better to wait a background thread to terminate before exiting an application.
The thread will eventually terminate and Windows will clean up any memory left over. However, you might as well just wait for the thread to terminate, because that is exactly what Windows will do anyway. Your application may appear to have shut down because all windows may have been closed/hidden, but the application process won't terminate until all threads have finished...
When a process terminates the OS will reclaim all allocated memory and will close all open handles. You don't need to worry about MEMORY*) that leaks in the very special event of shutting down the application. The OS will also close all your open handles**), at least theoretically. All those taken into account, it might be safe for you to simply terminate your thread (using TerminateThread(MyThread.Handle)) from your forms destructor, before killing other shared resources. Ask yourself those questions:
What's the thread doing? Is it safe to terminate it at any time? Example: If the thread is doing any writing to disk, it's unsafe to just kill it, because you might live files on disk in an inconsistant state.
Are you using any resources that aren't automatically freed by Windows? Can't think of an good example here...
If you're on the safe side with both, you can use TerminateThread and not wait for the thread to naturally terminate. A safer approach might a combined approach, maybe you should give the thread a chance to naturally terminate and, if it didn't terminate withing 5 seconds, force-terminate it.
*) I'm talking about memory you can prove only leaks on process termination, like threads you kill without giving them a chance to properly shut down, or global singleton classes you don't free. All other unaccounted memory needs to be tracked down and fixed, because it's an bug.
**) Unfortunately the Windows OS is not bug-free. Example: Anyone that worked with serial devices on the Windows platform knows how easy it is to get the serial-device in a "locked" state, requiring an restart to get it working again. Technically that's also an Handle, end-processing the application that locked it should unlock it.
why you dont increment a variable when creating the thread, and on the destroy event wait until thread finish, decrement the variable, and on applicationterminate just do Application.processmessages ?
why your thread isn't freeonterminate=true ? all shared resources can be handled into a critical section.
best regards,
I am using Lucene.Net-2.3.2.1 in my project. My project also supporting multithreading environment. Lucene Indexing service is working as Windows Service. Problem is when the service is running, it's memory blockage is gradually increasing. So after some hours, it shows a memory of 150 mb in Task Manager where as it start with 13 mb.so it has a memory increasing behavior. I identified by dotTrace Profiler that in Lucene.Net there are some methods and objects that increased the memory. From Call Tree one of my dotTrace out identify that Index(), Segment() related functions hold's memory increased as long as the service perform. So it at a time, it will crash the system.
Please help me how i can recover my application from this memory leakage.
Increasing memory usage doesn't necessarily implies a memory leak. Memory leaks in .NET are not that common, but there are a few options you should check
Events. Make sure that all event listeners are detached from the publisher as soon as they are no longer used. Failing to do so will keep the listeners alive as long as the publisher is alive.
If the code uses any disposable resource that holds handles to native code, be sure to call Dispose on these as soon as they are no longer needed.
A blocking finalizer will prevent other finalizable objects from being garbage collected, so make sure finalizers don't do any more than they have to (and in many cases they are probably not needed anyway).
If you want to examine which objects are being kept alive as well as why they are not collected, I recommend using WinDbg + Sos.