【问题标题】:Memory leak sqlite3MemMalloc in iphone appiphone应用程序中的内存泄漏sqlite3MemMalloc
【发布时间】:2014-02-06 08:51:21
【问题描述】:

我在 iphone 的仪器工具中发现 sqlite3Memmalloc 泄漏。我的应用程序消耗超过 200 MB 的内存。在内存管理工具中,它将责任库显示为 libsqlite3.dylib,责任调用者显示为 sqlite3MemMalloc。在我的应用程序中,我试图插入 2000 行。我认为由于内存使用,应用程序崩溃了。我已经检查了各个方面,但无法在我的 sqlite 代码中找到错误泄漏。请给我一个解决方案。下面是我的sqlite代码。

- (Boolean) insertQuotes:(QuotesInfo*)quote
  {

NSString *dbPath = [dBManager GetConnectToDatabase];
sqlite3_stmt *selectstmt=nil;
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
    if(selectstmt == nil)
    {

        NSString* Query=[NSString stringWithFormat:@"insert into Quotes (QuoteID,QuoteDate,QuoteDesc,QuoteAuthor,QuoteCategory,QuoteCategoryID,QuoteAuthorID,QuoteFavourite,QuoteCategoryFilterStatus,QuoteAuthorFilterStatus,AuthorFirstName,AuthorLastName) values (%d, '%@', %@, '%@', '%@', %d, %d, %d, %d, %d, '%@', '%@')",quote.quoteId,quote.quoteDate,quote.quoteDesc,quote.quoteAuthor,quote.quoteCategory,quote.quoteCategoryID,quote.quoteAuthorID,quote.quoteFav,quote.quoteCategoryFilterStatus,quote.quoteAuthorFilterStatus,quote.authorFirstName,quote.authorLastName];

        NSLog(@"Query %@",Query);
        const char *sql = [Query UTF8String];

        if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) != SQLITE_OK)
        {
            NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
        }
    }
    @try {

    }
    @catch (NSException * e) {

        return  NO;

        NSLog(@"INSERT EXCEPTION %@",e);
        //Handle the Exception here..
    }

    if(SQLITE_DONE != sqlite3_step(selectstmt)){
        NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
    }
    else{
        sqlite3_reset(selectstmt);
        sqlite3_finalize(selectstmt);
        sqlite3_close(database);
        return YES;
      }
    }
  return NO;
}

【问题讨论】:

    标签: ios iphone sqlite memory-leaks


    【解决方案1】:

    该代码中有很多可怕的错误,但与内存泄漏有关的错误是:

    • 你并不总是在sqlite3_prepare_v2 成功后调用sqlite3_finalize;和
    • 您并不总是在sqlite3_open 成功后调用sqlite3_close

    您不能将这些调用隐藏在某些 if/else 分支中。 重构您的代码,以便始终进行这些调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多