Search code examples
c++iteratorsegmentation-faultleveldbsstream

Segmentation fault while declaring an iterator in c++ example of leveldb


I was trying to apply an iteration to my leveldb file, but unfortunately I couldn't get the result. The problem that I'm facing is a segmentation fault in using the pointer of the iterator. I used gdb And I got that the problem is in the line

leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());

(I added before some values to this file /tem/userDb , and the add is working good .)

#include <assert.h>
#include <leveldb/db.h>
#include <iostream>
#include <sstream>
using namespace std;

void iteration(leveldb::DB* db)
{
    leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
    for (it->SeekToFirst(); it->Valid(); it->Next())
    {
        cout << "key :" << it->key().ToString() << " : "
             << "value:" << it - > value().ToString() << endl;
    }
    if (false == it->status().ok())
    {
        cerr << "An error was found during the scan" << endl;
        cerr << it->status().ToString() << endl;
    }
    delete it;
}

int main(int argc, char *argv[])
{
    leveldb::DB* db;
    leveldb::Options options;

    options.create_if_missing = true;

    // erase error if the database exists
    options.error_if_exists = true;
    leveldb::Status s = leveldb::DB::Open(options, "/tmp/userDb", &db);
    if (!s.ok()) 
        cerr << s.ToString() << endl;
    iteration(db);
    delete db;
}

Solution

  • Not familiar with the leveldb API, but you're using db regardless of whether s.ok() is true or false. I'd assume that if s.ok() is false, db is either NULL, or in a state such that iteration or other operations won't work.

    You should change the code to:

    if (!s.ok()) {
        cerr << s.ToString() << endl;
        return -1;
    }