user401383
user401383

Reputation: 401

memory leak with alloc

I have below code which is causing memory leak

-(NSString *) getSingRecord: (NSString *) getStatement{

NSString *sql=getStatement;

sqlite3_stmt *statement;

NSString *fieldFlagI=@"0";

if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil) == SQLITE_OK) {
    while (sqlite3_step(statement) == SQLITE_ROW) {
        char *fieldFlag=(char *) sqlite3_column_text(statement, 0);
        fieldFlagI=[[NSString alloc] initWithUTF8String:fieldFlag];
        //fieldFlagI=[NSString initWithUTF8String:fieldFlag];
    }
    sqlite3_finalize(statement);
}
//NSString *ffI=fieldFlagI;
//[fieldFlagI release]
return [fieldFlagI];
}

After checking apple documentation i changed code to return [fieldFlagI autorelease];

and in the code segment where i am calling this function

NSString *getRecord=[dbase getSingRecord:flag];

if i do a [getRecord release]; - application crashes - how do i release this object?

Upvotes: 0

Views: 217

Answers (2)

Alex Reynolds
Alex Reynolds

Reputation: 96937

Autorelease the fieldFlagI variable in the method, retain the getRecord result to take ownership of it so that you can release it later. Read through the Memory Management Guide for iOS.

Upvotes: 1

Girish Kolari
Girish Kolari

Reputation: 2515

If you do [fieldFlagI autorelease];then variable 'getRecord' don't own the object so you can not release.

once you add object to autorelease pool you can not release the object till you own the object by adding a retain count.

NSString *getRecord=[dbase getSingRecord:flag]; //object is in autorelease pool which will be released by pool
[getRecord retain] //own the object
//do some operation
[getRecord release] //then release

Upvotes: 1

Related Questions