0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
cucurbita
  • 31
  • 4

1 Answers1

0

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.

for_stack
  • 21,012
  • 4
  • 35
  • 48
  • Thank you for your answer, but it still doesn't seem to work for me. Not sure if hset() is able to take more than 3 arguments as it gives me following error: redis.cpp:19:36: error: no matching function for call to ‘sw::redis::Redis::hset(std::string, const char [4], char*&, const char [4], char&)’. trying to call "r.hset("key", "field", "value")" it still gives me a segmentation error. – cucurbita Jul 07 '23 at 22:17
  • alright, I think I fixed Segmentation fault. Yet I struggle to understand how to receive reply from HGETALL function. Could you explain how to print the result of r.hgetall("0", std::inserter(results, results.begin()) in terminal, please? – cucurbita Jul 07 '23 at 22:59
  • and the question with sending multiple fields into hset() remains open... – cucurbita Jul 07 '23 at 23:11