According to Instruments analysis, I have a memory leak here - and - I'm unsure as to how to properly release the scoresArray object that I have created.
This code does work properly, apart from the leakage. I release the highScoresArray object later in the code - but attempts to release the scoresArray kill the app. I thought that when I released highScoresArray, that I would release scoresArray, since they both point to the same location in memory. If anyone can point out where my thinking is flawed, that would be great.
- (void) readScoresFile {
// Read the Scores File, if it exists
NSString *filePath = [self scoresFilePath];
// Only load the file if it exists at the path
if ([[NSFileManager defaultManager] fileExistsAtPath: filePath]) {
scoresFileExistsFlag = YES;
NSLog(#"SCORES FILE EXISTS - THEREFORE LOAD IT");
NSMutableArray *scoresArray = [[NSMutableArray alloc] initWithContentsOfFile: filePath];
highScoresArray = scoresArray;
} else {
scoresFileExistsFlag = NO;
NSMutableArray *scoresArray = [[NSMutableArray alloc] init];
highScoresArray = scoresArray;
// No Scores File exists - we need to create and save an empty one.
int counter = 1;
while (counter <= 5) {
// Set up a date object and format same for inclusion in the Scores file
NSDate *now = [[NSDate alloc] init];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy.MM.dd"];
NSString *theDateNow = [dateFormat stringFromDate:now];
// Add the score data (Score and User and date) to the runScoreDataDictionary
runScoreDataDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:0], #"score",
[NSNumber numberWithInt:0], #"landings",
currentUser, #"user",
theDateNow, #"date", nil];
//NSLog(#"Dictionary contains: %#", runScoreDataDictionary);
// Add the dictionary to the highScoreArray
[highScoresArray addObject:runScoreDataDictionary];
//NSLog(#"OBJECTS in ARRAY: %i", [highScoresArray count]);
[self writeScoresFile]; // Write the empty scores file to disk
[now release];
[dateFormat release];
++counter;
//[scoresArray release]; // TESTING TO SEE IF THIS KILLS - YES KILLS
}
}
}
I'm guessing highScoresArray is an instance variable (since it's not declared anywhere in the method you listed). This means that upon creation of scoresArray (which is the same object as highScoresArray) it has a retain count of 1. You don't retain it, so releaseing it will decrement its retain count to 0 and it will be cleaned up -- not a good thing for an instance variable.
I'm also not sure why you do this:
NSMutableArray *scoresArray = [[NSMutableArray alloc] init];
highScoresArray = scoresArray;
You don't seem to need to use scoresArray anywhere else, so you could just do this:
[highScoresArray release]; // Release the old object
highScoresArray = [[NSMutableArray alloc] init];
I release the highScoresArray object later in the code - but attempts to release the scoresArray kill the app. I thought that when I released highScoresArray, that I would release scoresArray, since they both point to the same location in memory
As long as you haven't changed the highScoresArray pointer to point to another object, releasing it will be the same as releasing scoresArray.
NSMutableArray* highScoresArray;
NSMutableArray* scoresArray = [[NSMutableArray alloc] init];
highScoresArray = scoresArray;
[highScoresArray release]; // same as `[scoresArray release];`
But if you change either of them afterwards to point to another object, releasing them won't be equivalent:
NSMutableArray* highScoresArray;
NSMutableArray* scoresArray = [[NSMutableArray alloc] init];
highScoresArray = scoresArray;
// ... Now make `highScoresArray` point to another object ...
highScoresArray = [[NSMutableArray alloc] init];
// Now you should release both as they point to different objects.
[highScoresArray release];
[scoresArray release];
Of course, simply calling addObject doesn't alter the pointer. It changes the object being pointed to. Only reassigning the pointer to another object matters here.
Related
The basic structure of my program has the user select an item from a UITableView, which corresponds to a stored text file. The file is then read into an array and a dictionary, where the array has the keys (I know I can just get the keys from the dictionary itself, this isn't my question).
The view is then changed to a UISplitView where the master view has the keys, and the detail view has the items in the dictionary attributed to that key. In this case, it's a series of "Yes/No" questions that the user selects the answer to.
My problem is this: When I click on a cell in the UITableView (first screen), it works fine, the data is read in perfectly, and so on. When I go back to the UITableView and click on the same cell again, the program crashes. Here is the read-in-from-file method:
-(NSArray *)readFromFile:(NSString *)filePath{
// NSLog(#"Path was: %#", filePath);
NSString *file = [[NSString alloc] initWithContentsOfFile:filePath];
// NSLog(#"File was: %#", file);
NSScanner *fileScanner = [[NSScanner alloc] initWithString:file];
NSString *held;
NSString *key;
NSMutableArray *detailStrings;
NSMutableArray *keys = [[NSMutableArray alloc] init];
NSMutableDictionary *details = [[NSMutableDictionary alloc] init];
/**
This is where the fun stuff happens!
**/
while(![fileScanner isAtEnd]){
//Scan the string into held
[fileScanner scanUpToString:#"\r" intoString:&held];
NSLog(#"Inside the while loop");
// If it is a character, it's one of the Key points, so we do the management necessary
if ([[NSCharacterSet lowercaseLetterCharacterSet] characterIsMember:[[held lowercaseString] characterAtIndex: 0]]){
NSArray *checkers = [[NSArray alloc] initWithArray:[held componentsSeparatedByString:#"\t"]];
NSLog(#"Word at index 2: %#", [checkers objectAtIndex:2]);
if(detailStrings != nil){
[details setObject:detailStrings forKey:key];
[detailStrings release];
}
NSLog(#"After if statement");
key = [checkers objectAtIndex:2];
[keys addObject:(NSString *) key];
detailStrings = [[NSMutableArray alloc] init];
}
else if ([[NSCharacterSet decimalDigitCharacterSet] characterIsMember:[[held lowercaseString] characterAtIndex: 0]]){
NSArray *checkers = [[NSArray alloc] initWithArray:[held componentsSeparatedByString:#"\t"]];
NSLog(#"Word at index 1: %#", [checkers objectAtIndex:1]);
[detailStrings addObject:[checkers objectAtIndex:1]];
}
}
NSLog(#"File has been read in");
[details setObject:detailStrings forKey:key];
NSArray *contents = [[NSArray alloc] initWithObjects:(NSMutableArray *) keys, (NSMutableDictionary *) details, nil];
[detailStrings release];
return contents;
}
I've determined that the program crashes inside the
if(detailStrings != nil)
statement. I figure this is because I'm missing some memory management that I am supposed to be doing, but don't have the knowledge of where it's going wrong. Any ideas as to the problem, or why it is crashing without giving me a log?
detailStrings is not initialized when you enter the while loop. When you declare NSMutableArray *detailStrings; inside a method, detailStrings is not automatically set to nil. So when you do
if ( detailStrings != nil ) { .. }
it enters the if statement and since it is not initialized, it will crash when you access detailStrings.
Another thing is that detailStrings won't be initialized if it enters the else part of the loop first. That will cause a crash too. So based on your requirement, either do
NSMutableArray *detailStrings = nil;
or initialize it before you enter the while loop.
Deepak said truth. You should initialize detailStrings with nil first.
But there is second possible issue:
I recommend also to set nil after release, because in the next loop you may test nonexistent part of memory with nil.
if(detailStrings != nil){
[details setObject:detailStrings forKey:key];
[detailStrings release];
detailStrings = nil;
}
And the third possible issue: depending from incoming data you may go to the second part of IF statement first time and try to addObject into non-initialized array.
The fourth (hope last): you have memory leak with "checkers" arrays
Here's what I'm seeing:
//read in the file
NSString *file = [[NSString alloc] initWithContentsOfFile:filePath];
//create the scanner
NSScanner *fileScanner = [[NSScanner alloc] initWithString:file];
//declare some uninitialized stuff
NSString *held;
NSString *key;
NSMutableArray *detailStrings;
//initialize some stuff
NSMutableArray *keys = [[NSMutableArray alloc] init];
NSMutableDictionary *details = [[NSMutableDictionary alloc] init];
//begin loop
while(![fileScanner isAtEnd]){
//scan up to a newline
[fileScanner scanUpToString:#"\r" intoString:&held];
//see if you scanned a lowercase string
if ([[NSCharacterSet lowercaseLetterCharacterSet] characterIsMember:[[held lowercaseString] characterAtIndex: 0]]){
//make an array
NSArray *checkers = [[NSArray alloc] initWithArray:[held componentsSeparatedByString:#"\t"]];
//do a check... against an uninitialized value
if(detailStrings != nil){
//set a potentially uninitialized value into an array with an uninitialized key
[details setObject:detailStrings forKey:key];
At this point, you're pretty much hosed.
The fix:
properly initialize your variables
run the static analyzer
read the memory management programming guide
I cannot find this memory leak. I thought I had been releasing things properly. Here is the block of code in question.
- (void) createProvince:(NSString *) provinceName {
// if province does not exist create it
if ([self hasProvince: provinceName] == NO) {
// get the province object
NSPredicate *predicate;
predicate = [NSPredicate predicateWithFormat:#"Name == %#", provinceName];
NSMutableArray *provArray = [[NSMutableArray alloc] init];
[provArray setArray: [CoreDataHelper searchObjectsInContext:#"Province" :predicate :#"Name" :YES :[self managedObjectContext]]];
NSIndexPath *indexPath;
indexPath = [NSIndexPath indexPathForRow:0 inSection: 0];
[[self provinces] addObject: [provArray objectAtIndex: [indexPath row]]];
[provArray release];
// create a cities array to hold its selected cities
NSMutableArray *array = [[NSMutableArray alloc] init];
[[self cities] addObject: array];
[array release];
}
}
The leaks are here:
[[self provinces] addObject: [provArray objectAtIndex: [indexPath row]]];
NSMutableArray *array = [[NSMutableArray alloc] init];
[[self cities] addObject: array];
I am creating the local variables, assigning them to my instance variables through the proper setters, and then releasing the local variables. I am not sure what is going on.
Do you have a dealloc method that is properly releasing everything?
Note that leaks is showing you where something was allocated. It doesn't show you where it was actually leaked; what retain wasn't explicitly balanced.
Let's look at this:
NSMutableArray *array = [[NSMutableArray alloc] init];
[[self cities] addObject: array];
[array release];
When you alloc an object, its retain count is set to 1:
NSMutableArray *array = [[NSMutableArray alloc] init]; # retain count of array is 1
When you add an object to an NSMutableArray, that object's retain count is incremented:
[[self cities] addObject: array]; # retain count of array is 2
When you release the array, its retain count is decremented:
[array release]; # retain count is now 1
Once your method ends, you still have that array owned by the mutable array [self cities].
Because [self cities] doesn't appear to get released or emptied, this is where you get a leak.
You need to empty or release the mutable array at some point, releasing the objects contained within. If cities is a class property, perhaps release it when the class is released.
EDIT
Fixed init-alloc mistake.
Does the release, recursively releases all inner objects? or must it be done manualy?
Can I do just this?
NSMutableArray *list = [[NSArray alloc] init];
// ...
// fill list with elements
//...
[list release];
Or must I release all inner objects one by one before releasing the NSMutableArray? // Suposing there isn't any other reference to the contained objects, except on the list itself.
Yes it does. It retains them when added, and releases them when dealloc'd. This is actually one of the most common questions I see here.
If you are owning the object then you will have to release it.
NSMutableArray *list = [[NSArray alloc] init];
NSString *str = [[NSString alloc] init] // you are the owner of this object
[list addObject:str];
[str release]; // release the object after using it
[list release];
If you are not the owner of the object then you should not release.
NSMutableArray *list = [[NSArray alloc] init];
NSString *str = [NSString string]; // you are not owning this object
[list addObject:str]; // str retain count is incremented
[list release]; // str retain count is decremented.
This is the concept which even array also uses. When you add any object to the array, array will retain it. In the sense it becomes the owner of that object and It will release that object when you release the array.
I developing an application, in which i working with database manipulation. The method i have written in database class as follows.
-(NSMutableArray *)getData: (NSString *)dbPath{
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK){
NSString *sqlQuery = [NSString stringWithFormat:#"SELECT empID, addText FROM Employee WHERE nameID = %#", nameID];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, [sqlQuery UTF8String], -1, &selectstmt, NULL) == SQLITE_OK){
while (sqlite3_step(selectstmt) == SQLITE_ROW){
[dataArray addObject:[[NSMutableDictionary alloc] init]];
[[dataArray lastObject] setObject:[NSString
stringWithFormat:#"%d", sqlite3_column_int(selectstmt, 0)] forKey:#"empID"];
[[dataArray lastObject] setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,1)] forKey:#"addText"];
}
}
sqlite3_finalize(selectstmt);
}
sqlite3_close(database);
return dataArray;
}
The above code work fine on the simulator but cannot on device.
I also was tracing the memory leaks , in which i founding that memory leak in above method code. But i not able to solve the that memory leak.
Now i also find out memory leak in following method.
(id)initWithString:(NSString *)str attributes:(NSDictionary *)attributes
{
if ((self = [super init]))
{
_buffer = [str mutableCopy];
_attributes = [NSMutableArray arrayWithObjects:[ZAttributeRun attributeRunWithIndex:0 attributes:attributes], nil];
}
return self;
}
The leak near _buffer = [str mutableCopy];. And leak trace gives me in the output continuous increasing NSCFString string allocation. How i maintain it?
Thanks in advance.
Your leak is that you don't release either the dataArray object, nor the mutable dictionaries you create in the while loop. Consider autoreleasing the mutable array, and manually releasing the dictionaries after you add them to the array.
As for why it "doesn't work" on the device, you need to be more specific about what happens and why that isn't what you expect.
Your inner loop leaks the NSMutableDictionary objects, as you should release them after adding to the array, i.e.
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSString stringWithFormat:#"%d", sqlite3_column_int(selectstmt, 0)] forKey:#"empID"];
[dict setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,1)] forKey:#"addText"];
[dataArray addObject:dict];
[dict release];
Also, your whole method should most probably return an autoreleased object by naming convention. Not sure if this is a leak - depends on how you call that method and if you release the returned value.
So maybe use
return [dataArray autorelease];
From the first glance you have 2 places where leaks can be:
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
...
return dataArray;
Caller method is responsible for releasing array returned from your method - check if it does.
Also your method name is not consistent with obj-c guidelines - they suggest that methods returning non-autoreleased object( so caller is responsible for releasing them) should contain create, alloc, copy in their name. So it could be better to return autoreleased array (return [dataArray autorelease]; from this method and let caller decide whether it needs to retain array or not.
Second place is
[dataArray addObject:[[NSMutableDictionary alloc] init]];
It is leaking dictionary object, you should probably just write
[dataArray addObject:[NSMutableDictionary dictionary]];
Your method contains two call to +alloc that don't have corresponding calls to -release or -autorelease.
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
...
[dataArray addObject:[[NSMutableDictionary alloc] init]];
You can rewrite these lines like this to get rid of the leak:
NSMutableArray *dataArray = [NSMutableArray array];
...
[dataArray addObject:[NSMutableDictionary dictionary]];
With an instance variable myArray:
#interface AppController : NSObject
{
NSArray *myArray;
}
Sometimes I see myArray initialized like this:
- (void)init
{
[super init];
self.myArray = [[NSArray alloc] init];
return self;
}
and sometimes I see it with a more complicated method:
- (void)init
{
[super init];
NSArray *myTempArray = [[NSArray alloc] init];
self.myArray = myTempArray
[myTempArray release];
return self;
}
I know that there's no difference in the end result, but why do people bother to do the longer version?
My feeling is that the longer version is better if the instance variable is set up with a #property and #synthesize (possibly because the variable has already been alloced). Is this part of the reason?
Thanks.
If myArray is a property and it's set to retain or copy (as it should be for a property like this), then you'll end up double-retaining the variable when you do this:
self.myArray = [[NSArray alloc] init];
The alloc call sets the reference count to 1, and the property assignment will retain or copy it. (For an immutable object, a copy is most often just a call to retain; there's no need to copy an object that can't change its value) So after the assignment, the object has retain count 2, even though you're only holding one reference to it. This will leak memory.
I would expect to see either a direct assignment to the instance variable
myArray = [[NSArray alloc] init];
Or proper handling of the retain count:
NSArray *newArray = [[NSArray alloc] init];
self.myArray = newArray;
[newArray release];
Or the use of autoreleased objects:
self.myArray = [[[NSArray alloc] init] autorelease]; // Will be released once later
self.myArray = [NSArray array]; // Convenience constructors return autoreleased objects
This is an idiom used in mutators (sometimes called "setters"), but I think you typed it slightly wrong. Usually it looks like this:
-(void)setMyName:(NSString *)newName
{
[newName retain];
[myName release];
myName = newName;
}
The new name is retained, since this instance will need to keep it around; the old name is released; and finally the instance variable is assigned to point to the new name.
I have a feeling you mean this:
NSArray* a = [NSArray arrayWithObjects:#"foo", #"bar", nil];
and this
NSArray* a = [[NSArray alloc] initWithObjects:#"foo", #"bar", nil];
//...
[a release];
With the first style, the static method performs an alloc/init/autorelease on it for you so you don't have to. With the second style, you have more control over when the memory is released instead of automatically releasing when you exit the current block.
That code will crash your application. The second version only copies the pointer then releases the instance. You need to call [object retain] before releasing the reference.