Pergunta

I implemented the following GBDM example:

#include <boost/lexical_cast.hpp>
#include <gdbm.h>
#include <iostream>
#include <string>
#include <string.h>

struct record
{
    int a;
    int b;
};

int main(int argc, char* argv[])
{
    GDBM_FILE db;

    db = gdbm_open("gdbm.db", 512, GDBM_WRCREAT | GDBM_NOLOCK | GDBM_SYNC, 0664, NULL);

    datum lekey;
    datum levalue;
    for (int i = 0; i < 10; ++i) {
        record r;
        r.a = i;
        r.b = i + 1;
        lekey.dptr = (char*) boost::lexical_cast<std::string>(i).c_str();
        lekey.dsize = strlen(lekey.dptr) + 1;
        levalue.dptr = (char*) &r;
        levalue.dsize = sizeof(record);
        gdbm_store(db, lekey, levalue, GDBM_INSERT);
    }
    gdbm_sync(db);

    for(lekey = gdbm_firstkey(db);
        lekey.dptr != NULL;
        lekey = gdbm_nextkey(db, lekey)) {
        levalue = gdbm_fetch(db, lekey);
        record* r = (record*) levalue.dptr;
        if (r) {
            std::cout << lekey.dptr << " " << r->a << " " << r->b << std::endl;
            free(levalue.dptr);
        }
    }

    gdbm_close(db);

    return 0;
}

The output is the following:

$ ./gdbm_example 
3 3 4
6 6 7
2 2 3
9 9 10
5 5 6
1 1 2
8 8 9
4 4 5

Why would 0 0 1 and 7 7 8 be left out? Is this a bug or am I doing something wrong?

Foi útil?

Solução

A problem might be this line:

lekey.dptr = (char*) boost::lexical_cast<std::string>(i).c_str();

This stores the pointer to a temporary variable, and so is undefined behavior.

The key doesn't have to be a string, it can as well be a number, so you can use e.g.:

lekey.dptr = &i;
lekey.dsize = sizeof(i);

Outras dicas

Joachim is right, using boost::lexical_cast is out of place here. Rewrite your example using this:

std::string s;
std::stringstream str;
str << i;
s = str.str();
lekey.dptr = (char*) s.c_str();

and it will work as expected.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top