Receiving reply in hiredis

199 views Asked by At

I'm trying to check if I'm filling redis database using hiredis correctly.

Via redisCommand() I send it HSET <key> <filed> <value> first, then HGETALL <key>, expecting to have command callback at reply->str, but reply->str remains inaccessible.

Here's the part of code where I try to check if the filling is right:

const char* redisHostname = "127.0.0.1";
int redisPort = 6379;

redisContext* redis = redisConnect(redisHostname, redisPort);
const char* argv[] = { "HSET", std::to_string(i).c_str(), "lat", lat.c_str(), "lon", lon.c_str()};
    redisReply* reply;
    reply = (redisReply*)redisCommandArgv(redis, 6, argv, NULL);        
    
    if (i % 10000 == 0) { //for check
        std::cout << i << " " << lat << " " << lon << std::endl;
        std::cout << reply << std::endl;
    }
    freeReplyObject(reply);
}
redisReply* reply = (redisReply*)redisCommand(redis, "HGETALL 0");

Printing the reply shows 0x7fffe6eb2be0 value, and reply->str causes a segmentation error.

So in short my question is how do I check for the redis command callback in Hiredis?

PS: I know that hiredis is a C redis client, yet I don't think launching it with C++ gives unexpected errors.

1

There are 1 answers

3
for_stack On

HSET returns an integer reply, and HGETALL returns an array reply. Neither returns a string reply. So reply->str is not a valid string pointer, and you should not access it.

If you want to check HSET's reply, you should print reply->integer.

Since you use C++, you can try redis-plus-plus, which is a user-friendly Redis C++ client. Rewrite your code with redis-plus-plus:

auto r = sw::redis::Redis("redis://127.0.0.1");
for (auto i = 0; i < N; ++i) {
  auto res = r.hset(std::to_string(i), lat", lat, "lon", lon);
  if (i % 10000 == 0)
    cout << res << endl;
}
std::unordered_map<std::string, std::string> results;
r.hgetall("0", std::inserter(results, results.begin()));

Disclaimer: I'm the author of redis-plus-plus.