Memory Leak Issue in Windows Phone Develoment - Silver Light Framework - windows-phone-7

I am creating one game in Windows phone using c# and silver light platform. I am new in this technology and currently facing memory leak issue.
As per research and study I have done, I have tried to do all the things including events, string and usage of garbage collector.
Can any one please give common tips to best utilize garbage collector and memory management since it seems issue right now. When my garbage collector reaches 5 lac size, it stop collecting new things and application is getting crash.
I also tried empty the garbage collectore passing parameter 0 in gc collect but it is crashing the app.
Can you please guide and help for basic things to take care, process to follow to avoid such issues and best use of GC collect?
Thanks in advance,
Jacob

In general, you should never have to call GC.Collect yourself as unused objects will be automatically collected every few seconds.
As for what can prevent objects from being collected, it comes down to them being "rooted". Roots include:
Any static references
Any references held by the run loop (your Application is the closest thing here)
Anything being displayed on the current page or any page behind it
Anything referenced by any of the above (including UI events), or referenced by anything that is referenced by any of the above (etc).
In the above scenarios, those objects and any objects they hold a reference to cannot be GC'd. So as for advice:
Avoid defining anything as static
Be careful how many objects are held by Application
Avoid a navigation model that allows your back stack to grow to ulimited levels
Potentially look at setting references to large data sets to null in your page/viewmodel's OnNavigatedFrom method and re-initialise them in OnNavigatedTo
I'd recommend using the Windows Phone Profiler, which comes with the 7.1 SDK. It will tell you what objects are in memory and why.

Without seeing any of your code, it is difficult to give specific advice.
However, I strongly suggest you run a memory profiling tool like ANTS Memory Profiler or .Net Memory Profiler. These tools will show you what portions of your code are never released and are very helpful in making the adjustments that you need.

Related

Why does Titanium Alloy have so many leaks?

Why does instruments using the leaks tool show so many leaks and then crash after about three leak detection cycles?
That cannot be normal ?
The app I am testing on has one index window with one label in it which, on click opens another window which on click closes itself again.
No big deal yet it seems to have leaks ?
the first detection says 72 new leaks
the second then 8 new leaks ... ?
Does anyone know why this might be ?
Thanks for your help trying to get my head around this
Having developed apps with Titanium for 8 years now this doesn't look anything like it should. Whenever leaks are found by the community it usually is quickly fixed by the dev team. That said, it is very rare leaks are found.
Most memmory leaks are developer generated. For example if you create references to UI elements outside the controller it is in you will have to clean up the reference to that UI element to let garbage collection handle it. Garbage collection cannot trigger if you didn't free the components up.
I will not be able to help you further besides the above as you have not provided any relevant information like SDK version, code that causes it etc. You might've stumbled upon a real memory leak but chances are you're not freeing up resources.

Out of Memory Message box

I have an MFC application developed with VS2003
It is working fine in XP vista etc.
But when i have executed it in windows 8, and we use it for some time,
then no window is displayed. Instead of that the a MessageBox with a message 'Out of Memory' is displayed. And the Message box is Having the caption of my application.
This issue is rarely occurred in windows 7 too.
I have tried watching the handles using tools like processexplorer and it is not increasing.
Also many forums says that it is because of increase in unclosed handles or resources.
Can any one suggest how can i find where the issue is. Or any one provide possible reason for this.
I cant setup the devenv in the machine causing the issue. I am confused how to diagnose by executing a test build in that.
Please provide your findings.
Thanks in advance.
You clearly have a memory leak somewhere. It's hard to be any more specific without seeing the code.
A debugger is really the best way to solve this problem. If you can reproduce the problem on your development machine, that would be the easiest case. If not, you can attach a debugger to the running process on another machine, either locally or remotely.
The MFC libraries also support some basic memory leak detection, turned on by default for Debug builds and controllable for other builds using the AfxEnableMemoryTracking function. You can use this feature to obtain information about which blocks of memory were allocated but not properly deallocated (i.e. were leaked).
Like you mentioned, Process Explorer is another good way to track down resource leaks. Are you sure that the handle counts are remaining constant rather than trending upwards over time? If the values in the columns are never changing like the question suggests, then you are surely doing something wrong. Your application has to be creating objects in order to do its job. The point is to make sure that it disposes of them when it is finished.
If you can't reproduce the problem with the running application and have only the source code available, you'll need to go through the code and make sure that every use of new has a corresponding use of delete (and that new[] matches up with delete[]). And in general in C++, you should avoid explicit dynamic memory allocation wherever possible. Instead, use the container classes that are provided either by MFC or the standard library. For example, don't allocate arrays manually, use std::vector to do it for you. These container classes ensure that the memory is automatically deallocated in the destructor when the object goes out of scope.

Win32 application windows eventually stop painting on Windows 7

I have a large, complex application written in C++ (no MFC or .NET). The client that uses the software most aggressively will, within an hour or so of starting it, get to a state where all the windows stop painting. We get reports that the application has "hung" because as far as they can tell nothing is happening. In reality, the application is functioning, just not displaying anything.
I've tried a lot of different things to no avail. I'm out of ideas...
You probably already have a hunch of what it is - you give it away in the first sentence
... large, complex application ...
It sounds like you have a GDI resource leak somewhere. To confirm this try looking in task manager at GDI objects for your process. At some point most GDI operations will fail for your application.
Make sure you are freeing all handles correctly. Note that different GDI objects require different methods of freeing the object. For example GetDC is freed by ReleaseDC, but CreateDC is freed by DeleteDC.
This is why RAII smart objects (like smart pointers) are recommended for resource management in C++ (where freeing is managed by the smart object to reduce the likelihood of leaks and errors).
I'd bet that the application is leaking GDI objects, and when the GDI dedicated space for this process is exhausted, it can no longer paint itself.
You can check if this is the case by adding to the Windows Task Manager (or any other process manager such as Process Monitor) the column GDI Objects and see if this number grows unbounded with time.
Your application may actually be suffering from an exception that is getting ignored. See Microsoft KB article 976038.

Can you start and stop boundschecker (DevPartner)?

I'm trying to use boundschecker to analyze a rather complex program. Running the program with boundschecker is almost too slow for it to be of any use since it takes me almost a day to run the program to the point in the code where I suspect the issue exists. Can anyone give me some ideas for how to inspect only certain parts of my software using boundschecker (DevPartner) in Visual Studio 2005?
Thanks in advance for all your help!
I last used BoundsChecker a few years ago, and had the same problems. With large projects, it makes everything run so slowly that it is useless. We ended up ditching it.
But, we still needed some of it's functionality, but like you, not for the whole program. So we had to do it ourselves.
In our case, we mainly used it to try and track down memory leaks. If that's your objective as well, there are other options.
Visual Studio does a pretty good job of telling you about memory leaks when your program exits
It reports leaks in the order that they were created
It will tell you exactly where the leaked memory was created if your source files have this at the top
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
Those help a lot, but it's often not enough. Adding that snippet everywhere isn't always feasible. If you use factory classes, knowing where memory was allocated doesn't help at all. So when all else fails, we take advantage of #2.
Add something like the following:
#define LEAK(str) {char *s = (char*)malloc(100); strcpy(s, str);}
Then, pepper your code with "LEAK("leak1");" or whatever. Run the program, and exit it. Your new leaked strings will display in Visual Studio's leak dump surrounding the existing leaks. Keep adding/moving your LEAK statements and re-running the program to narrow your search until you've pinpointed the exact location. Then fix the leak, remove your debugging leaks, and you're all set!
BoundsChecker tracks all memory allocations and releases in extreme detail. It knows, for instance, that such and such a memory allocation was done from the C runtime heap, which in turn was taken from a Win32 heap, which in turn started life as memory allocated by VirtualAlloc. If the application was instrumented (FinalCheck), it also has detailed information as to which pointers reference the memory.
This is one reason (of many) why the thing is slow.
If BC were to connect to an application late, it would have none of this data built up, and would have either (1) dig it all up at once, or (2) start guessing about things. Neither solution is very practical.
One way to lighten up BoundsChecker is by excluding from instrumentation all but the few modules you are interested in. I know thats not great because if you knew where the leak was you wouldn't need BoundsChecker. What I usually recommend is that you use BC's Active Check mode first with only Memory Tracking available. You miss the API Validations but you could always rerun that seperately. After you run Active Check and you get clues regarding which modules tend to be problematic, only then do you enable instrumentation for the module or modules of interest and their dependencies. We know Final Check is annoyingly slow but as Mistiano correctly states, with Final Check not only does BC keep a graph of all allocated blocks but also all pointers and contexts to them. Therein lies the magic in how Final Check can nail leaks and corruptions at the point of occurance, not just on application shutdown or fault. Shameless plug: I work on the DevPartner team. We are releasing DPS 10.5 on February 4, 2011 with x64 application support in BC. Unlike the relatively ancient and undersold BC64 for Itanium which only provided Active Check, DPS 10.5 provides full Final Check support for x64 applications, both for pure C++ and for native modules running in .NET processes. See microfocus.com under MF Developer for details.

Finding GDI/User resource usage from a crash dump

I have a crash dump of an application that is supposedly leaking GDI. The app is running on XP and I have no problems loading it into WinDbg to look at it. Previously we have use the Gdikdx.dll extension to look at Gdi information but this extension is not supported on XP or Vista.
Does anyone have any pointers for finding GDI object usage in WinDbg.
Alternatively, I do have access to the failing program (and its stress testing suite) so I can reproduce on a running system if you know of any 'live' debugging tools for XP and Vista (or Windows 2000 though this is not our target).
I've spent the last week working on a GDI leak finder tool. We also perform regular stress testing and it never lasted longer than a day's worth w/o stopping due to user/gdi object handle overconsumption.
My attempts have been pretty successful as far as I can tell. Of course, I spent some time beforehand looking for an alternative and quicker solution. It is worth mentioning, I had some previous semi-lucky experience with the GDILeaks tool from msdn article mentioned above. Not to mention that i had to solve a few problems prior to putting it to work and this time it just didn't give me what and how i wanted it. The downside of their approach is the heavyweight debugger interface (it slows down the researched target by orders of magnitude which I found unacceptable). Another downside is that it did not work all the time - on some runs I simply could not get it to report/compute anything! Its complexity (judging by the amount of code) was another scare-away factor. I'm not a big fan of GUIs, as it is my belief that I'm more productive with no windows at all ;o). I also found it hard to make it find and use my symbols.
One more tool I used before setting on to write my own, was the leakbrowser.
Anyways, I finally settled on an iterative approach to achieve following goals:
minor performance penalties
implementation simplicity
non-invasiveness (used for multiple products)
relying on as much available as possible
I used detours (non-commercial use) for core functionality (it is an injectible DLL). Put Javascript to use for automatic code generation (15K script to gen 100K source code - no way I code this manually and no C preprocessor involved!) plus a windbg extension for data analysis and snapshot/diff support.
To tell the long story short - after I was finished, it was a matter of a few hours to collect information during another stress test and another hour to analyze and fix the leaks.
I'll be more than happy to share my findings.
P.S. some time did I spend on trying to improve on the previous work. My intention was minimizing false positives (I've seen just about too many of those while developing), so it will also check for allocation/release consistency as well as avoid taking into account allocations that are never leaked.
Edit: Find the tool here
There was a MSDN Magazine article from several years ago that talked about GDI leaks. This points to several different places with good information.
In WinDbg, you may also try the !poolused command for some information.
Finding resource leaks in from a crash dump (post-mortem) can be difficult -- if it was always the same place, using the same variable that leaks the memory, and you're lucky, you could see the last place that it will be leaked, etc. It would probably be much easier with a live program running under the debugger.
You can also try using Microsoft Detours, but the license doesn't always work out. It's also a bit more invasive and advanced.
I have created a Windbg script for that. Look at the answer of
Command to get GDI handle count from a crash dump
To track the allocation stack you could set a ba (Break on Access) breakpoint past the last allocated GDICell object to break just at the point when another GDI allocation happens. That could be a bit complex because the address changes but it could be enough to find pretty much any leak.

Resources