Question

I am using the following function to loop through a couple of open CDB hash tables. Sometimes the value for a given key is returned along with an additional character (specifically a CTRL-P (a DLE character/0x16/0o020)).

I have checked the cdb key/value pairs with a couple of different utilities and none of them show any additional characters appended to the values.

I get the character if I use cdb_read() or cdb_getdata() (the commented out code below).

If I had to guess I would say I am doing something wrong with the buffer I create to get the result from the cdb functions.

Any advice or assistance is greatly appreciated.

char* HashReducer::getValueFromDb(const string &id, vector <struct cdb *> &myHashFiles)
{

  unsigned char hex_value[BUFSIZ];
  size_t hex_len;

  //construct a real hex (not ascii-hex) value to use for database lookups
  atoh(id,hex_value,&hex_len);

  char *value = NULL;
  vector <struct cdb *>::iterator my_iter = myHashFiles.begin();
  vector <struct cdb *>::iterator my_end = myHashFiles.end();


  try
  {
    //while there are more databases to search and we have not found a match
    for(; my_iter != my_end && !value ; my_iter++)
    {
      //cerr << "\n looking for this MD5:" << id << " hex(" << hex_value << ") \n";
      if (cdb_find(*my_iter, hex_value, hex_len)){
          //cerr << "\n\nI found the key " << id << " and it is " << cdb_datalen(*my_iter) << " long\n\n";
          value = (char *)malloc(cdb_datalen(*my_iter));
          cdb_read(*my_iter,value,cdb_datalen(*my_iter),cdb_datapos(*my_iter));
          //value = (char *)cdb_getdata(*my_iter);
          //cerr << "\n\nThe value is:" << value << " len is:" << strlen(value)<< "\n\n";
        };

    }
  }
  catch (...){}
  return value;
}
Was it helpful?

Solution

First, I am not familiar with CDB and I don't believe you include enough details about your software environment here.

But assuming it is like other database libraries I've used...

The values probably don't have to be NUL-terminated. That means that casting to char* and printing it will not work. You should add a 0 byte yourself.

So malloc cdb_datalen + 1 and set the last character to 0. Then print it.

Better yet, use calloc and it will allocate memory already set to zero.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top