Possible causes of memory error - ios

I’m having a memory issue. I get an error message “Thread 1: EXC_BAD_ACCESS(code=1,address=…) The error is elusive, and apparently timing-dependent. On my iPad mini, it usually averages about 3 minutes between crashes, on my iPhone SE it averages 10 minutes, and on the simulator it has run for 20 hours without crashing.
I’m not successful in using the Zombie detector. (See below for my experiences with it.) So I’m trying to go over my code with a fine tooth comb to see what might be causing the crash. What are the issues that might cause an allocation error?
My app is multi-threaded. It takes sound from the microphone, processes it, and continuously updates the display with the processed results. It’s written in Swift 3, so I’m not doing any explicit mallocs or frees.
I’m looking for places in the code that might cause an error. The two things I’m looking closest at are weak references and unsafe pointers. Are there any other common programming errors that could trip me up?
(The Zombie detector is useless. The Apple Instruments User Guide says, “For iOS apps, use the Zombies template with the iOS Simulator, rather than a physical device.” I’ve ignored the warning and tried it with my iPad mini, and I can’t get it to crash. Everything runs at about 1/10 speed, and when I pause the recording, my OSX machine gets sluggish as well, displaying the spinning “Wait” cursor for minutes at a time. The total memory allocation goes up and down, but stays within limits, so there is no major memory leak. I’ve also run the Zombies instrument on the simulator as well. It’s equally sluggish, and it still doesn’t crash.)

The issue in this case turns out to be thread safety. If I set a UInt8 variable on one thread and read it on another thread, it can lead to a memory error. The setters and the getters are not thread safe.
(I’ve been programming computers most of my professional life, mostly in C, C++, and Java. I’m familiar with the multi-threading issues in these languages. I’m new to Swift 3. It simply hadn’t occurred to me up to now that setting and getting numeric variables was not an atomic operation — that an ill-timed access could cause a program to crash. I’m going to have to drastically rethink my approach to concurrency with Swift.)

Related

Instruments: Leaks and Allocations (tvOS)

I’m currently working on a tvOS app. This is my first native (Swift) app. The app will be a digital signage app, used during events or in offices of companies.
One big difference compared to a typical app on iOS/tvOS is that it needs to run pretty much 24/7, so memory is a big topic for this app. The smallest leak will eventually cause the app to crash.
The app is constantly looping through a set of fullscreen slides. At the bottom of the screen there is a ticker with 10 articles (refreshed every 10 seconds - now during development). Below is a screenshot of the weather slide, to get an idea.

Currently the app is crashing after a period of time and I’m pretty sure I’ve narrowed it down to the ticker component (when disabling it, the app lives for days). If I use the ‘Leaks’ preset in Instruments I get the following result:

It looks like it’s leaking Article instances. I’m recreating Article instances every 10 seconds and providing them to the ticker component. I think that is why new instances leak every ~10 seconds.
Before I started using the ‘Leaks’ preset in Instruments, I used the ‘Allocations’ preset, while using this all seemed fine to me. But I’m probably misreading the results…
Using allocations:

The way I read this is that currently 10 Article instances exist in memory, and 31 have existed but are cleaned up now - so I’m safe.
But the app still crashes.
I’ve read a lot on retain cycles, implemented weak/unowned where I believe I should.
So my question is not so much about code, but more about how to read this data, what does a Leak mean in this context, and why do I see these ‘leaks’ not as persistent objects in the Allocations window?
(tests are done on multiple devices + simulator)
If you see a steady (i.e., approximately n GB / minute or hour) increase in memory usage in Instruments, that is a good sign that objects are being created, but not dealloced. Your allusion to weak and unowned vars makes me think that you know this, but you may not have found all sources of your leak. I would suggest taking a few generation summaries in Instruments, and looking at specific classes/objects in Heap allocations. Your problem classes will steadily increase in number, and likely never decrease. Try to debug the problem from there.
As for what 'leak' means in this context, it's what it always means: Your computer is not releasing memory resources. It may seem different, because we are used to thinking of a leak as something that eats through memory at a much faster rate (like an infinite loop running on four cores, or something), but that kind of leak and this are actually the same thing; yours is just slower.
I’m back after weeks trying to figure out what was wrong. The good news, I found my leak, and solved it!
The issue was solved by removing a closure inside another closure keeping a reference to a variable in the first closure. This caused a retain cycle.
I really don’t understand why I didn’t find it earlier, I asked a new question for this here: getting-different-data-in-instruments-based-on-method-of-profiling.

Why Is iOS App Causing Memory Leak in Xcode When Idle?

I am writing a game in Swift using SpriteKit with Xcode 7.3 on a Mac mini running El Capitan (both updated in last couple of days).
Shortly after I started, my Mac mini started crashing. The error log indicated that a Kernel Panic had occurred likely due to a memory leak & the process was identified as Xcode. Looking at the Activity Monitor, I can see that when this specific app is loaded in Xcode, the memory used by Xcode fairly rapidly increases even though the App is just sitting there doing nothing.
When other apps are loaded & idle, the memory usage stays more or less constant as you would expect. I have Googled for clues for several hours but can find only info. about memory leaks when an App is running & how to detect them with Instruments.
This is a weird one as far as I'm concerned. I do not have any idea how to start to figure out what's causing this other than starting with a fresh project & gradually adding code to see if/where it starts happening again. I would appreciate any ideas other Xcode users may have.
You don't happen to have
skView.showPhysics = true
turned on?
That is know to be causing memory issues exactly as you described.
There are a number of things you can do to start diagnosing this issue. Firstly you say that only one app is doing this. So this would indicate that the problem is an app problem rather than XCode. This is a good thing :-)
Next I would start using the profiler to monitor the memory and allocated objects in the app. try taking snap shots of the memory at regular intervals and look at what has been allocated since the prior snap shot. The profiler can then help you to dig down into the leaking objects and see where they are being retained and released. This might give you the clue you need.
Another thing is try is the profilers leaks monitoring. That also might tell you whats going on inside your app.
Lastly, is there anything in your code that is executing in some sort of loop. Something that animates on the home screen for example. Perhaps that is leaking.
Thanks very much to Drekka & Adrian B for your speedy answers but, as always happens, as soon as I post a question, I stumble across some information that leads to an understanding & (in this case partial) solution. Looking for an answer to a different question, I came across a thread on the Apple Developers Forum where several others are reporting the same issue.
It is related to the use of the SpriteKit Scene Editor. Hence it is app related in that for me it occurred with the only app for which I have ever used the Scene Editor but in reality it is an Xcode bug. What happens is that if the Scene Editor window is open (i.e. the .sks file is selected), even if the scene is blank, Xcode starts to leak memory at a rate of about 1MB/sec. If you close that window, the leakage stops. It happens even if Xcode is minimized. Apparently, it has been reported as a bug. I guess the work around for now is to accept the leakage while you're modifying your scene & then close the editor when you've finished (or do everything in code).
Cheers,
RB

iOS ARC ram grows up only [duplicate]

This question already has answers here:
Problems with memory management, autorelease, permanent heap is sometimes 250+ kb on iOS
(2 answers)
Closed 9 years ago.
Hello my question is maybe General I am not asking for code etc.
I developing only for iPhones with iOS6.1 and above
When I run my application the RAM it uses only grows up(when I switching between views (I have like 15 views)).
However after I ran test with analyzer it didn't find any leaks.
also no leaks were found in instrument leaks.
Despite my application doesn't exceed 20 mb of RAM I am still worried that something may be just not ok there.
I am using ARC ,but the ram still goes up.
Is there any way I can check what can cause 1 sided ram allocation ?
If the memory continues to go up, it could be a variety of different things, but "strong reference cycle" is the prime suspect. Sadly, this won't necessarily show up in Leaks tool in Instruments, either.
Do snapshots/generations in the Allocations tool and identify what's not getting released (notably if it consists of any of your classes) and go from there. Specifically, run the app through its paces, then mark snapshot/generation, do a bit more, and then mark another snapshot/generation. Look at that second snapshot and see what's been allocated (but not released) captured since the prior snapshot, with a focus on your classes. You'll find the culprit pretty quickly that way.
See WWDC video iOS App Performance: Memory for practical demonstration.
For example, here is a healthy app that I profiled through the Instruments' "Leaks" tool, but I'm going to focus on the "Allocations" tool:
In this profile, I waited for the app to quiet down, tapped on "Mark Generation" button (resulting with "Generation A", the first flag in my timeline). I then went to a view and then dismissed it, and did "Mark Generation" again, getting "Generation B". The "Growth" column is telling me that between Generation A and B, 100kb was consumed, but not released. But I'm not worried about this yet because there might be some iOS internal cache of UIKit elements. So, I repeat this process one more time to get "Generation C". Now that's interesting, now reporting a growth of only 8.26kb, which is negligible. This, combined with a clean bill of health from the Leaks instrument makes me feel pretty good about the risk of any serious memory problems.
Now, let's contrast that with some code that has a seriously problematic "strong reference cycle":
Now this is a completely different picture, even though the process was the same "present and dismiss" process, repeated twice. This is now telling me that I had a 14mb growth between generations, and more notably, I can clearly see the problematic growth curve. What's remarkable is that while the Allocations tool is clearly catching a serious problem, the Leaks tool reports nothing.
Now, in practice, the real-world experience with the Allocations tool will probably rest somewhere between these two extremes. Your app may have its own caches or model objects that slowly take up memory, but if you're properly responding to memory warnings, you should be recovering that memory. Frankly, though, most well designed apps should not be generating memory warnings at all (usually accomplished by properly configuring caches, avoiding imageNamed where appropriate, moving to persistent storage for large or infrequently accessed data, etc.). The goal is to get to a point where the app stabilizes around some reasonable baseline memory allocation level, consistently returning back to that baseline.
But it's going to be impossible for us to advise you until you do some basic profiling of your app and diagnose the sorts of memory issues that you're having.

iOS 7 app freezes without crash

I have an app that I am building for iOS 7 only and running on an iPhone 5S. The app sometimes in normal use just freezes up and won't recognize any touch interactions happen and it requires the app to be force quit. I have noticed it doing many different tasks and in different views. I have had this problem while debugging and the RAM usage is at about 65 Mb which I think is pretty good, cpu usage is in the single digits and the debugger doesn't register a crash. Where can I go from here in terms of debugging and trying to fix this pretty serious problem?
To put my comment as an answer, usually when your application freezes, it means either the CPU is doing some heavy lifting or your have a deadlock somewhere. As you mentioned that it was the CPU usage was low, my first guess was a deadlock.
Thanks to Leo Natan for suggesting that it was deadlocks, because it was. There was a specific instance where I was saving and fetching from the background thread and there was an easy solution that made it possible for me to stop fetching on the background thread.
For me, it was an endless while loop. Found it out by pausing the process and checking out the stack trace.

Core Text occasionally fails to produce results [iOS]

I’m helping out a company with a project for iOS, which is using Core Text. Some users of the app have reported that text is occasionally missing from within the app. It seems™ that this is somewhat memory related, because it’s solvable by shutting down the app along with background apps.
I made a few lines of code which simulates the use of the app – so the app “runs itself”, navigating between view controllers randomly, scrolling in text fields etc – to track if this issue occurs by normal use.
I’ve found some memory leaks related to the use of Core Text, but according to instruments the amount of memory lost is quite low. However, when the simulation has been running for about 20 minutes or so, the app is shut down by the os because of memory warnings.
I’m intending to fix this memory leaks, but my problem is that I will not be able to ensure that this fixes the main bug (missing text), since I cannot reproduce it myself.
So my final question is: have anyone experienced issues with missing text on iOS while using Core Text, which are due to leaked memory? Does it sound plausible? If so, is this related to only specific versions of iOS?
I appreciate any answers that can help me out!
UIViewControllers may implement didReceiveMemoryWarning that the system calls when your app is on low memory. Framework classes, as core text, are most likely do implement this and act accordingly to save memory. So it is possible that your core text object aims to help your app resolving the low-mem situation with freeing some of its resources that can even cause it to blank its contents. Fix first all memory leaks in your app.
On the other hand, all bugs are very difficult to correct if you can't reproduce them. If you suspect that the issue is due to low memory, try to simulate this yourself by allocating huge amount of memory in your application and hope that you can reproduce the erroneous behavior that way.

Resources