Skip to content

Instantly share code, notes, and snippets.

@michael-grunder
Created September 12, 2019 17:36
Show Gist options
  • Save michael-grunder/3d20c1a5190f8401c8f0ce438717d6f3 to your computer and use it in GitHub Desktop.
Save michael-grunder/3d20c1a5190f8401c8f0ce438717d6f3 to your computer and use it in GitHub Desktop.
Store replies somewhere else
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis/hiredis.h>
void printReplies(char **replies, size_t len) {
for (size_t i = 0; i < len; i++) {
printf("[%zu]: '%s'\n", i, replies[i]);
}
}
void freeReplies(char **replies, size_t len) {
for (size_t i = 0; i < len; i++) {
free(replies[i]);
}
}
char *_strdup(char *s, size_t len) {
char *r = malloc(len + 1);
memcpy(r, s, len);
r[len] = '\0';
return r;
}
int main(int argc, const char **argv) {
redisContext *c = redisConnect("127.0.0.1", 6379);
char *replies[10] = {0};
size_t num_replies = 0;
redisReply *r;
for (int i = 0; i < 10; i++) {
r = (redisReply*)redisCommand(c, "PING %d", i);
if (r) {
if (r->type == REDIS_REPLY_STRING) {
// I'm storing `r->str` into another structure that I use later
// so we must duplicate this memory since `freeReplyObject` will
// free it below.
replies[i] = _strdup(r->str, r->len);
num_replies++;
}
freeReplyObject(r);
}
}
printReplies(replies, num_replies);
// We also must remember to free our duplicated memory
freeReplies(replies, num_replies);
redisFree(c);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment