Dump all allocated objects - objective-c

I'm looking a way to print all allocated objects when I get
applicationDidReceiveMemoryWarning
Is there someway I can see what objects are in memory. An system-api call, A framework, anything really.
I'm aware of Clang & debugging by code-inspection but I'm looking for a way to see at run-time why I have a memory leak.
Suggestions?
Thanks :)

Use the Instruments Allocations tool. You can navigate and see all live objects.

You can use instruments->leaks tool to see where you have a leak. It's quite precise and you can see where you allocated the object.

I don't know of a way to do this at runtime without keeping track of all the objects yourself. If you're doing this during debugging, you can pause execution at that point and take a "heapshot" of your process using Instruments. That will show you everything that's been allocated on the heap.

Related

NSZombies enabled, debug information

My Mac app is crashing with exc_bad_access on the run loops.
So I enabled NSZombies, and Now I don't see such error as expected ( As the objects are not de-allocated).
But, I don't find any useful NSZombie Log in the console.
Is there a way to identify the issue ?
It's challenging. The most common cause of this error in Cocoa is directly accessing your ivars rather than using accessors. Accessors make the vast majority of memory crashes go away.
That said, they're not the only cause of memory errors. You may be accessing memory other ways. NSZombie does one specific thing: When you deallocate an object, NSZombie says "don't actually deallocate the object." Instead it turns the object into a zombie object that prints an error if you send it messages. But that only helps if the crash is due to sending a message to a deallocated instance. It could be lots of other things.
You should start first with the crash stack itself. Look up the stack and see what kind of object it might be, or who might be calling it.
Read TN2124, particularly the section on the BSD Memory Allocator, and the Enabling the Malloc Debugging Features section of the memory Usage Performance Guidelines. There are lower-level tools than NSZombie that you can use. MallocScribble is often the most useful. It overwrites deallocated memory with 0x55 so that you're more likely to crash sooner, and to make it easier to detect deallocated memory in the debugger. MallocPreScribble is useful for finding uninitialized memory, but this really only helps if you do raw malloc calls. ObjC objects are always pre-initialized.
And of course you have to put on your detective hat. What parts of your program are most suspicious? Are you doing multi-threaded work (that can cause memory crashes if you don't lock correctly).
If it reproduces easily, then you'll figure it out. If it only happens occasionally, well... I've hunted bugs like that for many months sometimes. Sometimes it's just hard.
You need to use memory profiler for that. Just build with Profile option and select Leaks.

Problems with memory management, autorelease, permanent heap is sometimes 250+ kb on iOS

I'm really pulling my hair out on this one, it seems that I'm having severe issues with memory management on an iOS app.
Here's the case: first I load table. When the user taps a cell, it presents a complicated view. The most memory consuming about the view is that it's loading 20+ UIImages of 500x500. There are two other tabs in that view, loading a list of media (those UIImages, but then in a table) and another simple table.
When I return back to the first table view, apparently over 250 kB is still allocated on heap. I know the view is complicated, but there's no reason to keep so much memory alive. And well, guess what, when I do switch to the view a lot, eventually the app runs out of memory and gets killed.
What I tried to solve it:
Fix all Analyze issues, so according to that there are no leaks anymore.
Check all inits again for releasing, making use of autorelease where possible.
Checking all the memory leaks using Instruments -> Leaks. In a runtime of 6, I get not more than 2 or 3 leaks.
Last, Instruments -> Allocation, checking the heap. This is what bothers me, between two marked heapshots I get a difference of 250+ kB. I've looked into it, using the detailed views. I can't get my head around it: when it's pointing to one of my methods/classes, I'm pretty sure everything in there is either released or autoreleased. It's also pointing to a lot of not-mine (say QuartzCore) methods/classes.
Also, I don't understand why autorelease is not autoreleasing. I mean, it sometimes looks like an object that is marked for autoreleasing, is released way too late. I haven't created any NSAutoreleasePools myself, so is it possible that the pool is drained only when the runtime stops? How can I periodically drain the pool (even if it's not mine).
Any help is greatly appreciated.
Kind regards,
Reinder
Used this for the heap checking: http://www.friday.com/bbum/2010/10/17/when-is-a-leak-not-a-leak-using-heapshot-analysis-to-find-undesirable-memory-growth/
Are you using imageNamed to load your images - this method will keep all images cached in memory. Try initWithContentsOfFile instead.
Watch out though; initWithContentsOfFile: won't cache at all so if you use this method a lot for the same image then you should be using imageNamed:!
I think you might want to try to optimize your design first and read guides for efficent memory management. A better understaning of the components and the runtime helps more than tracking memory allocations and will make it easier to find the leaks.
First you should always use release. Only use autorelease when necessary.
Make sure you follow the guidelines for UITableView implementations and efficient management of UITableViewCells (lazy loading, cell reusing etc.).
Check if you have retain-cycles (retained view controllers won't be deallocated).
Track the deallocation of your view controllers and objects
Don't keep stuff in memory you don't need anymore.
Don't load stuff you don't need right now.

When should I release memory?

How do I decide when I should release memory? Because If I release the memory, many times the application crashes.
You should release memory when you've finished with it. Objects are reference counted so, as long as you retain and release (and everyone else does too), you should have no problems.
If you find you're crashing because you release the memory, then either you or someone else isn't following the rules.
In either case, find out who isn't following the rules, and fix it. Don't hold on to memory just to avoid crashes. That way lies madness (and lack of memory).
Try the apple documentation on memory management in objective-c.
http://developer.apple.com/mac/library/documentation/cocoa/conceptual/MemoryMgmt/MemoryMgmt.html
Read Memory Management Programming Guide.

How do I debug weird memory management issues in Xcode/Objective-C?

I'm newish to Objective-C and my memory management skills are not great. However, I haven't had a single problem until now. And now I've got big problems.
I've gone from zero crashes to crashing at random points, giving me either no console output or unrecognized selector errors on random types (-[NSCFSet isSameAsStop:]: unrecognized selector - I don't even use any sets and I surely have not called my custom isSameAsStop on any sets.). Judging by the randomness and errors, it seems like a memory thing to me although I'm not entirely sure.
How do I go about debugging this? The debugger assumes you know where your problem is... and mine is just everywhere. Ideas?
SOLUTION COMMENT
Some clarification on the solution suggestion to "run with zombie detection enabled":
Set the NSZombieEnabled to YES on the Executables' Arguments screen.
Build and then choose Run with Performance Tool > Object Allocations, which will start Instruments.
Click the "i" button on Object Allocations in Instr. and select zombie detection and retain counts.
Rerun and click around in your app, it'll tell you when you hit a zombie!
Thanks for the help!
You have a classic over-release bug on your hands. Somewhere, you are over-releasing an instance of the class that implements isSameAsStop and it just so happens that an NSSet instance is allocated at the same spot after the original instance is deallocated.
The first step is to "build and analyze" your code, fixing any problems that the static analyzer finds.
The next step is to then run with zombie detection enabled.
In Xcode: Build menu >> Build and Analyze
Finds a lot of common memory management issues.

Avoiding, finding and removing memory leaks in Cocoa

Memory (and resource) leaks happen. How do you make sure they don't?
What tips & techniques would you suggest to help avoid creating memory leaks in first place?
Once you have an application that is leaking how do you track down the source of leaks?
(Oh and please avoid the "just use GC" answer. Until the iPhone supports GC this isn't a valid answer, and even then - it is possible to leak resources and memory on GC)
In XCode 4.5, use the built in Static Analyzer.
In versions of XCode prior to 3.3, you might have to download the static analyzer. These links show you how:
Use the LLVM/Clang Static Analyzer
To avoid creating memory leaks in the first place, use the Clang Static Analyzer to -- unsurprisingly -- analyse your C and Objective-C code (no C++ yet) on Mac OS X 10.5. It's trivial to install and use:
Download the latest version from this page.
From the command-line, cd to your project directory.
Execute scan-build -k -V xcodebuild.
(There are some additional constraints etc., in particular you should analyze a project in its "Debug" configuration -- see http://clang.llvm.org/StaticAnalysisUsage.html for details -- the but that's more-or-less what it boils down to.)
The analyser then produces a set of web pages for you that shows likely memory management and other basic problems that the compiler is unable to detect.
If your project does not target Mac OS X desktop, there are a couple of other details:
Set the Base SDK for All Configurations to an SDK that uses the Mac OS X desktop frameworks...
Set the Command Line Build to use the Debug configuration.
(This is largely the same answer as to this question.)
Don't overthink memory management
For some reason, many developers (especially early on) make memory management more difficult for themselves than it ever need be, frequently by overthinking the problem or imagining it to be more complicated than it is.
The fundamental rules are very simple. You should concentrate just on following those. Don't worry about what other objects might do, or what the retain count is of your object. Trust that everyone else is abiding by the same contract and it will all Just Work.
In particular, I'll reiterate the point about not worrying about the retain count of your objects. The retain count itself may be misleading for various reasons. If you find yourself logging the retain count of an object, you're almost certainly heading down the wrong path. Step back and ask yourself, are you following the fundamental rules?
Always use accessor methods; declare accessors using properties
You make life much simpler for yourself if you always use accessor methods to assign values to instance variables (except in init* and dealloc methods). Apart from ensuring that any side-effects (such as KVO change notifications) are properly triggered, it makes it much less likely that you'll suffer a copy-and-paste or some other logic error than if you sprinkle your code with retains and releases.
When declaring accessors, you should always use the Objective-C 2 properties feature. The property declarations make the memory management semantics of the accessors explicit. They also provide an easy way for you to cross-check with your dealloc method to make sure that you have released all the properties you declared as retain or copy.
The Instruments Leaks tool is pretty good at finding a certain class of memory leak. Just use "Start with Performance Tool" / "Leaks" menu item to automatically run your application through this tool. Works for Mac OS X and iPhone (simulator or device).
The Leaks tool helps you find sources of leaks, but doesn't help so much tracking down the where the leaked memory is being retained.
Follow the rules for retaining and releasing (or use Garbage Collection). They're summarized here.
Use Instruments to track down leaks. You can run an application under Instruments by using Build > Start With Performance Tool in Xcode.
I remember using a tool by Omni a while back when I was trying to track down some memory leaks that would show all retain/release/autorelease calls on an object. I think it showed stack traces for the allocation as well as all retains and releases on the object.
http://www.omnigroup.com/developer/omniobjectmeter/
First of all, it's vitally important that your use of [ ] and { } brackets and braces match the universal standard. OK, just kiddin'.
When looking at leaks, you can assume that the leak is due to a problem in your code but that's not 100% of the fault. In some cases, there may be something happening in Apple's (gasp!) code that is at fault. And it may be something that's hard to find, because it doesn't show up as cocoa objects being allocated. I've reported leak bugs to Apple in the past.
Leaks are sometimes hard to find because the clues you find (e.g. hundreds of strings leaked) may happen not because those objects directly responsible for the strings are leaking, but because something is leaking that object. Often you have to dig through the leaves and branches of a leaking 'tree' in order to find the 'root' of the problem.
Prevention: One of my main rules is to really, really, really avoid ever allocating an object without just autoreleasing it right there on the spot. Anywhere that you alloc/init an object and then release it later on down in the block of code is an opportunity for you to make a mistake. Either you forget to release it, or you throw an exception so that the release never gets called, or you put a 'return' statement for early exit somewhere in the method (something I try to avoid also).
You can build the beta port of Valgrind from here: http://www.sealiesoftware.com/valgrind/
It's far more useful than any static analysis, but doesn't have any special Cocoa support yet that I know of.
Obviously you need to understand the basic memory management concepts to begin with. But in terms of chasing down leaks, I highly recommend reading this tutorial on using the Leaks mode in Instruments.