EXC_BAD_ACCESS in objective c - objective-c

Could someone help me with code below? Randomly get EXC_BAD_ACCESS in this loop. I guess there something wrong with [NSString stringWithFormat:....], but don't understand why and don't know how to fix. Thank you very much.
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
CGRect tileFrame=CGRectMake(i*tileSize, j*tileSize, tileSize, tileSize );
UILabel * t=[[UILabel alloc]initWithFrame:tileFrame];
t.text=[NSString stringWithFormat:#"%i",j*row+i];
///If there is a crashing ,it always stop at here, right after the [NSString stringWithFormat:.....]
t.backgroundColor=[UIColor clearColor];
//NSString * temps=[NSString stringWithFormat:#"%i",j*row+i ];
//t.text=temps;
[myView addSubview:t];
[t release];
}
}
BTW, I read some post online, I was told to do it in the way below can fix the problem. I'm not sure about this, why need to retain an autorelease object when this object is still in its scope. And more important shouldn't I release the retain object somewhere? Otherwise there will cause a memory leaking.
replace
t.text=[NSString stringWithFormat:#"%i",j*row+i];
with:
NSString * temps=[NSString stringWithFormat:#"%i",j*row+i ];
[temps retain];
t.text=temps;

i have tested it in my device and it is not crashing .
i have added 't' in self.view , i think there may be a problem with myView

This error is because you work with an object which was released previously. Try to setup these settings:
They are in Project >> Edit Scheme >> Arguments
Then place the console output here.

Related

Crash when trying to present UIActivityViewController

I see a crash in Crashlytics than happens to my users sometimes. The crash happens when presenting UIActivityViewController in the last line of the following code:
NSData* snapShot = ... ;
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:[NSArray arrayWithObjects:activityTextsProvider, snapShot ,nil] applicationActivities:[NSArray arrayWithObjects:customActivityA, customActivityB, customActivityC, nullptr]];
activityViewController.excludedActivityTypes = [NSArray arrayWithObjects:UIActivityTypePrint, UIActivityTypeAssignToContact, UIActivityTypeMail, UIActivityTypeCopyToPasteboard, nil];
activityViewController.popoverPresentationController.sourceView = self.myButton;
activityViewController.popoverPresentationController.sourceRect = self.myButton.bounds;
activityViewController.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError)
{
...
};
[self presentViewController:activityViewController animated:YES completion:nil];
I perform this in the main thread and unable to reproduce this crash locally. What could be the reason of this crash?
Edit: I changed nullptr to nil and the issue still happened. I managed to reproduce the issue: the crash happens only if before opening the activity controller i showed a UIMenuController. When creating UIActivityViewController it is not nil, but when presenting the controller i see the crash in the presentViewController line and the activity controller there is shown as nil
József addressed the use of nullptr in comments, and Fogh is spot-on that the actual crash log is important (please edit your question and post the full crash log), but I'd like to point out something else.
You're assuming your call to initialize activityViewController is succeeding. You should code defensively (by assuming everything that can fail probably will fail and testing for this at runtime). Wrap the rest of the configuration and presentation inside an if (activityViewController != nil) {} condition (you should probably have an else with proper error handling/reporting too) so you're properly detecting an all-out initialization failure for multiple reasons (like a misplaced nib, missing resource, etc.).
In your case, I think it's likely the initialization is failing because your class is doing something with a faulty array, as József's nullptr catch suggests. Perhaps you're using one or more pre-C++11 c libraries / compiling with a non-C11/gnu11 "C Language Dialect" build setting and nullptr is not equivalent to nil, leading to strange results in a supposed-to-be-nil-terminated array?
Note: If that turns out to be the case, I'll happily take an upvote but would rather József post his comment as an answer so you can give him proper credit. (Feel free to edit this request out of my answer if/when that happens.)

NSImageView - Huge memory leak?

For some reason, the allocation of two NSImageViews creates a huge memory leak.
Although dealloc method gets called in both NSImageViews.
I'm using ARC.
With NSImageViews
As soon as the following getter method is called, a lot of memory is used.
This would be ok, but it doesn't get deallocated when the window is being closed...
- (NSView *)animationView {
if (!_animationView) {
_animationView = [[NSView alloc] initWithFrame:self.bounds];
self.oldCachedImageView = [[NSImageView alloc] initWithFrame:self.bounds];
[_animationView addSubview:self.oldCachedImageView];
self.oldCachedImageView.wantsLayer = YES;
self.cachedImageView = [[NSImageView alloc] initWithFrame:self.bounds];
[_animationView addSubview:self.cachedImageView];
self.cachedImageView.wantsLayer = YES;
self.animationView.wantsLayer = YES;
}
return _animationView;
}
The first circle is when the getter method above is called.
The second is when the window is deallocated.
Without NSImageViews
Not with the two NSImageViews commented out.
- (NSView *)animationView {
if (!_animationView) {
_animationView = [[NSView alloc] initWithFrame:self.bounds];
/*
self.oldCachedImageView = [[NSImageView alloc] initWithFrame:self.bounds];
[_animationView addSubview:self.oldCachedImageView];
self.oldCachedImageView.wantsLayer = YES;
self.cachedImageView = [[NSImageView alloc] initWithFrame:self.bounds];
[_animationView addSubview:self.cachedImageView];
self.cachedImageView.wantsLayer = YES;
self.animationView.wantsLayer = YES;
*/
}
return _animationView;
}
No memory leak here...
Anyone an idea why this happens?
Use Instruments to trace the "Leaks". There is a Leaks tool in Instruments. Run it through the use of your app, all the way until you close your it completely. Make sure ARC isn't just deallocating it at a later time, which is possible. Keeping it in memory for a while allows for a faster retrieval if needed again.
However, if you do see a leak displayed, then there is an issue. Make sure there are no references to it you aren't noticing.
Use the leaks tool to figure out the memory location that is leaking if it displays some. Then try to match it with some object in your code. In other words, make sure it is the NSImageView that is leaking.
You can use:
NSLog(#"Location = %#",NSObjectHere);
To get the memory location. If it matches, then go back, once more, and find the reference you have to it. Unless it's an ARC bug, which is possible, though unlikely, then you are holding a reference to it somewhere.
For any more detail, please update your question with more code, no one can debug it for you without seeing more code.
Good luck!
EDIT
Tutorial explaining the use of the Leaks tool at http://mobileorchard.com/find-iphone-memory-leaks-a-leaks-tool-tutorial/

NSZombiEnabled settings

I am trying to check NSZombieEnabled is working in my code.
I've the following settings :
and I've the following code in didFinishLaunchingWithOptions
NSString *string = nil;
[string release];
string = #"abc";
but, there is no error generated. there is no notification from NSZombie as well. Should I do some more settings. Please help me, cause I've a lib that I've imported and there is a EXC_BAD_ACCESS with code 13 happening, and I am not able to get to the error cause.
The stack and the console looks like this
Your settings are correct, but your code does not create any zombies. A zombie is an object which has been freed, but is re-used. Something like this will create a zombie:
NSString* string = [NSString stringWithString:#"abc"];
[string release];
[string length];
In this example, the string is released, and then you attempt to use it by calling its length method.
In the case of your library, what does the stack look like when it gives you the EXC_BAD_ACCESS?

Can I use autorelease to fix this memory leak?

I have a memory leak in my iPhone app. I added Google AdMob to my app using sample code downloaded from Google. However, I was having a hard time getting it into testing mode so I added an extra variable as follows:
GADRequest *r = [[GADRequest alloc] init];
r.testing = YES;
[bannerView_ loadRequest:r];
I found the memory leak using Instruments. Instruments does not lead me to this line of code, it just dumps me in the main.m file. However, when I comment out the code relating to AdMob the leak goes away and I know enough to see that I haven't taken care of releasing this new variable. I just don't know exactly how I should set about releasing it. The variable r is not addressed in the header file so this is all the code that deals with it.
I tried adding:
- (void)dealloc {
[r release];
....
}
but that caused a build error saying "'r' undeclared". That's weird because it looks to me like I'm declaring r in the first quoted line above but I guess that's wrong. Any help would be much appreciated. I really have tried to educate myself about memory leaks but I still find them very confusing.
Just add [r release]; right below the code:
GADRequest *r = [[GADRequest alloc] init];
r.testing = YES;
[bannerView_ loadRequest:r];
[r release];
The variable r is declared only in that section of your code, so that's where it should be released. The point of releasing is to get rid of it as soon as you no longer need it, so the above should work perfectly for you.
If your r is locally declared (as it seems, judging from your snippet), then it cannot be accessed from outside its scope (here: the method it was declared in).
You either need to make it accessible within your class instance by declaring it an ivar.
Declaring it an ivar would look like this:
#interface YourClass : SuperClass {
GADRequest *request;
}
//...
#end
You then change your code to this:
request = [[GADRequest alloc] init];
request.testing = YES;
[bannerView_ loadRequest:request];
Also don't forget to release it in dealloc:
- (void)dealloc {
[request release];
//...
}
However this is not what you want in this situation (I've just included it to clarify why you get the warning about r not being declared).
You (most likely) won't need request any second time after your snippet has run, thus storing it in an ivar will only needlessly occupy RAM and add unwantd complexity to your class. Stuff you only need at the immediate time after its creation should be taken care of (released) accordingly, that is within the very same scope.
What you'll actually want to do is simply (auto)release it, properly taking care of it.
Keep in mind though that your loadRequest: will need to take care of retaining r for as long as it needs it. Apple's implementation does this, of course. But you might want to write a similar method on your own one day, so keep this in mind then.
GADRequest *r = [[GADRequest alloc] init];
r.testing = YES;
[bannerView_ loadRequest:r];
[r release]; //or: [r autorelease];
OP here. Thanks for all the detailed and thoughtful responses. This has definitely helped get a better handle on memory management. I did exactly as recommended, adding [r release]; right below the posted code. However, I still have a leak. I have isolated it to a single line of code. The following leaks:
GADRequest *r = [[GADRequest alloc] init];
r.testing = YES;
[bannerView_ loadRequest:r];
[r release];
The following does not leak:
GADRequest *r = [[GADRequest alloc] init];
r.testing = YES;
// [bannerView_ loadRequest:r];
[r release];
I figure I'm changing the retain count on bannerView with the loadRequest but I don't know how to fix it. I tried a [bannerView_ release] immediately after the [r release]; line (i.e. releasing locally) but that didn't work. I didn't expect it to because bannerView_ is declared elsewhere. I tried [bannerView_ release]; in the dealloc method but that didn't work. I also tried [bannerView_ autorelease]; locally. The wise heads at Google put [bannerView_ release]; in the ViewDidUnload method.
It's possible that Instruments is just messing with my head. The leak appears after about 10 seconds but the app performs well and the amount of memory leaked doesn't seem to be spirally upwards as the app continues to run. Is there such a thing as a benign memory leak?
Thanks again for your help,
Dessie.

Objc memory crash with autorelase

I have been hunting all over my code and can't find the source of this crash:
I am trying to decode an object with an NSKeyedUnarchiver and it crashes on it every time and says:
*** __NSAutoreleaseFreedObject(): release of previously deallocated object (0x1008ad200) ignored
*** __NSAutoreleaseFreedObject(): release of previously deallocated object (0x1008ab200) ignored
*** __NSAutoreleaseFreedObject(): release of previously deallocated object (0x1008a8c00) ignored
Ha my bad the reason why initWithCoder was not getting called was it was having issues with the [super initWithCoder:]; This is still driving me crazy. I looked and the pointers and the NSData objects are what are going wrong:
vertices = malloc(size_point3D * vertexCount);
textureCoords = malloc(size_point2D * textureCount);
normals = malloc(size_point3D * normalCount);
faces = malloc(sizeof(GLuint) * faceCount);
NSData *vertexData = [[NSData alloc] initWithData:[coder decodeObjectForKey:#"vertices"]];
NSData *textureData = [[NSData alloc] initWithData:[coder decodeObjectForKey:#"textureCoords"]];
NSData *normalData = [[NSData alloc] initWithData:[coder decodeObjectForKey:#"normals"]];
NSData *faceData = [[NSData alloc] initWithData:[coder decodeObjectForKey:#"faces"]];
memcpy(vertices, [vertexData bytes], sizeof(point3D) * vertexCount);
memcpy(textureCoords, [textureData bytes], sizeof(point2D) * textureCount);
memcpy(normals, [normalData bytes], sizeof(point3D) * normalCount);
memcpy(faces, [faceData bytes], sizeof(GLuint) * faceCount);
[vertexData release];
[textureData release];
[normalData release];
[faceData release];
I have tried retaining everything in this part (even the string) but it does not help.
This was a hard one to solve partly because debugging memory behaves inconsistently.
I have 2 classes JGStaticModel and JGModel. For some reason, the unarchiver would pick one of those at random so sometimes initWithCoder was sent to JGModel and not JGStaticModel. This led me to think it was not being called. Also since their structure is slightly different it had issues and crashed. The reason why I got the autorelease problem was I patched some memory problems in JGStaticModel but not JGModel so it would crash on the memory because I had not fixed it there.
Thanks for all the help!
Try turning on NSZombieEnabled, this should help you track down the problem.
If neither tools (Run -> Run with Performance tools) and NSZombiesEnabled helps, you can override - (id)retain and - (void)release methods of the class that caused the exception. Call super implementation and log retain/release. You can break in this methods to see the call stack. This way isn't beautiful, however, it helped me few time to figure out where was an extra release/autorelease call
This problem is very easy to solve with the solution given here.
The relevant part is:
If an environment variable named "NSAutoreleaseHaltOnFreedObject" is set with string value "YES", the function will automatically break in the debugger