1

I'm having trouble getting a char* string from a passed struct. I have the following code:

typedef struct {
    NSInteger id;
    char *title;
} Movie;

...

Movie movie = [self randomMovie];

NSInteger movieID = movie.id;
NSString *movieTitle = [NSString stringWithUTF8String:movie.title];
NSLog(@"movieTitle: %@", movieTitle);

...

- (Movie)randomMovie {
sqlite3_stmt *statement;
NSString *query = @"SELECT id, title FROM movies ORDER BY RANDOM() LIMIT 1;";

Movie movie;

if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
    if (sqlite3_step(statement) == SQLITE_ROW) {
        // Get the id and title of the first
        movie.id = sqlite3_column_int(statement, 0);
        movie.title = (char *)sqlite3_column_text(statement, 1);
    }
}

NSLog(@"Random movie %d title: %@", movie.id, [NSString stringWithUTF8String:movie.title]);

sqlite3_finalize(statement);
return movie;
}

This gives me the output:

2013-03-13 10:10:39.438 Fabflix[89156:c07] Random movie 872011 title: Ray
2013-03-13 10:10:39.439 Fabflix[89156:c07] movieTitle: (null)

Does anyone know why the title string isn't being passed correctly from randomMovie? Thanks!

0

2 Answers 2

2

I'm not terribly familiar with the sqlite3 C API, but are you sure the sqlite3_finalize() call isn't destroying the C string returned from sqlite3_column_text()? You may need to strdup() that thing (and then remember to free() it later).

Update: Yep, from the docs:

The pointers returned are valid until a type conversion occurs as described above, or until sqlite3_step() or sqlite3_reset() or sqlite3_finalize() is called. The memory space used to hold strings and BLOBs is freed automatically.

Sign up to request clarification or add additional context in comments.

Comments

1

The memory returned by sqlite3_column_text is released as soon as you call sqlite3_finalize. You need to copy the value to your own string first.

typedef struct {
    NSInteger id;
    NSString *title;
} Movie;

/* ... */

movie.title =
    [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.