简体   繁体   中英

My code snippet is leaking

The below code snippet leaks when i am trying the build and analyse thing.

What is the problem in this code , pls let me know

- ( NSString *) getSubCategoryTitle:(NSString*)dbPath:(NSString*)ID{
        NSString *subCategoryTitle;

    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) 
    {
        NSString *selectSQL = [NSString stringWithFormat: @"select sub_category_name from sub_categories where id = %@",ID];

        NSLog(@"%@ I am creashes here", selectSQL);

        const char *sql_query_stmt = [selectSQL UTF8String];

        sqlite3_stmt *selectstmt;

        if(sqlite3_prepare_v2(database, sql_query_stmt, -1, &selectstmt, NULL) == SQLITE_OK) 
        {

            while(sqlite3_step(selectstmt) == SQLITE_ROW) 
            {

                subCategoryTitle = [[NSString alloc] initWithUTF8String:
                                    (const char *) sqlite3_column_text(selectstmt, 0)];


            }
        }

        sqlite3_finalize(selectstmt);    

    }   
    sqlite3_close(database); 


    return [subCategoryTitle autorelease];
}

You allocate instance into subCategoryTitle in a loop, but don't release the previous allocation.

subCategoryTitle = [[NSString alloc] initWithUTF8String:
                                (const char *) sqlite3_column_text(selectstmt, 0)];

Either (auto)release it, or directly go to the last row, and avoid this while, as it doesn't make much sense.

Example for creating only last object:

char * col_text = NULL;
while(sqlite3_step(selectstmt) == SQLITE_ROW) 
{
    col_text = sqlite3_column_text(selectstmt, 0);
}
if (col_text != NULL)
{
    subCategoryTitle = [[NSString alloc] initWithUTF8String:col_text];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM