Guy Pnini
Guy Pnini

Reputation: 21

lost value of object in c++ sqlite callback function

these are the functions, after building the correct object inside fillAlbum data gets lost in openAlbum.

/*
the function will fill the album with correct values (callback function)
*/
int fillAlbum(void* data, int argc, char** argv, char** azColName)
{
    Album* album = new Album();
    album->setName(argv[1]);
    album->setCreationDate(argv[3]);
    album->setOwner(std::stoi(argv[2]));
    data = album;

    return 0;
}

/*
the function return the asked album
*/
Album DatabaseAccess::openAlbum(const std::string& albumName)
{
    Album album;
    char** errMessage = nullptr;
    std::string sqlStatement = "SELECT * FROM ALBUMS WHERE NAME LIKE '" + albumName + "';";
    sqlite3_exec(db_access, sqlStatement.c_str(), fillAlbum, &album, errMessage);
    return album;
}

Upvotes: 0

Views: 128

Answers (1)

freakish
freakish

Reputation: 56487

It gets lost (in fact it is worse: you have a memory leak!) because you don't use the callback correctly. You pass &album and now you have to cast the void* pointer and fill it, not overwrite it (in fact, the data = album line has no effect at all outside the fillAlbum function, you just overwrite a local variable). Try this:

int fillAlbum(void* data, int argc, char** argv, char** azColName)
{
    Album* album = static_cast<Album*>(data);  // <-- this line is crucial
    album->setName(argv[1]);
    album->setCreationDate(argv[3]);
    album->setOwner(std::stoi(argv[2]));
    return 0;
}

Upvotes: 1

Related Questions