SQLite Error : EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) -iOS

SQLite Error : EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) -iOS

当我尝试将数据插入我的 table 时,有时会出现此错误,并且我的应用程序崩溃了!

崩溃日志:

Observation(4001,0x10dd67000) malloc: *** error for object 0x7fff3a917100: Non-aligned pointer being freed (2)
*** set a breakpoint in malloc_error_break to debug
2016-11-03 11:12:03.063 Observation[4001:46477] Insertion failed !


Printing description of dbpath:
(const char *) dbpath = 0x00007fff3b8a5690 "/Users/macbt/Library/Developer/CoreSimulator/Devices/0EEC62AE-6DF0-4FC4-9D30-1EB90CB695A5/data/Containers/Data/Application/A709E729-3162-4CC8-B9FF-2F22A32FC6BD/Documents/ObservationDB.db"


Printing description of insertSQL:
insert into table_hazard (id, name, modifiedDate) values ("1","Hazard", "03/11/2016 11:12:03 AM")


Printing description of insert_stmt:
(const char *) insert_stmt = 0x00007fff3b9291a1 "insert into table_hazard (id, name, modifiedDate) values (\"1\",\"Hazard\", \"03/11/2016 11:12:03 AM\")"

我认为问题可能是由于同时在不同线程中访问数据库造成的。可以使用线程锁来解决这个问题。您可以在 @synchronized 块中编写数据库操作代码来解决这个问题。可以这样实现。

@synchronized (self) {
    // do the operation
}

请告诉我它是否有效。欢迎提出修改建议。

  • 尝试在malloc_error_break上设置断点。

  • 释放变量后将变量设置为 nil。

  • 仔细检查对 sqlite3_prepare_v2 指令的所有调用,并确保为每个指令调用匹配的 sqlite3_finalize

  • 添加 @synchroinized 块使其线程安全

sqlite实现去Fmdbhttps://github.com/ccgus/fmdb很容易理解

此类问题的解决方法是 ,您可能缺少以下语句。

 sqlite3_finalize(statement);
        sqlite3_close(database);

sqlite3_open()
sqlite3_prepare_v2()

我们应该始终在 return 语句之前完成语句并关闭数据库。不要让数据库保持打开状态。
如果您尝试再次打开它,则没有完成语句并且没有关闭数据库 sqlite3_open()

sqlite3_prepare_v2()

这将导致 EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) 关于数据库。

例如:

-(BOOL) insertDropdownValues:(NSString *)tableName
                       andId:(NSInteger) dID
                        name:(NSString*) name
                modifiedDate:( NSString*) modifiedDate {

    const char *dbpath = [databasePath UTF8String];

    if (sqlite3_open(dbpath, &database) == SQLITE_OK)
    {

        NSString *insertSQL = [NSString stringWithFormat:@"insert into %@ (%@, %@, %@) values (\"%ld\",\"%@\", \"%@\")",tableName,ID,NAME,MODIFIED_DATE, dID,name,modifiedDate];

        const char *insert_stmt = [insertSQL UTF8String];


        sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);


        if (sqlite3_step(statement) == SQLITE_DONE)
        {

            NSLog(@"Inserted SuccessFull");
            sqlite3_finalize(statement);
            sqlite3_close(database);

            return YES;
        }
        else {

            NSLog(@"Insertion failed !");
            sqlite3_finalize(statement);
            sqlite3_close(database);

            return NO;
        }

    }

    sqlite3_reset(statement);
    return NO;

}