Jack Humphries
Jack Humphries

Reputation: 13267

SQLite Encoding Issue

I am trying to read UTF8 encoded text from a SQLite database using the following code. However, the code will occasionally throw an EXC_BAD_ACCESS exception. This appears to be due to the sqlite3_column_bytes16 method call. If I replace the method call with a small number, such as 20, the exception is not thrown at all. What should I do to prevent this exception?

const unichar *text = sqlite3_column_text16(compiledStatement, 0);

if (text) {

   article = [NSString stringWithCharacters:text length:sqlite3_column_bytes16(compiledStatement, 0)];

}

Upvotes: 0

Views: 156

Answers (1)

Martin R
Martin R

Reputation: 539705

sqlite3_column_text16() return the number of bytes in the string, but stringWithCharacters:length: expects the number of characters as the second argument:

const unichar *text = sqlite3_column_text16(compiledStatement, 0);
if (text) {
   NSUInteger length = sqlite3_column_bytes16(compiledStatement, 0)/sizeof(unichar);
   article = [NSString stringWithCharacters:text length:length];
}

This error could go unnoticed in some cases because the string returned by sqlite3_column_bytes16() is always zero-terminated, but your code would read beyond the allocated buffer size and cause undefined behaviour.

Upvotes: 2

Related Questions