2011-12-16 714 views
0

我在使用Redis编写的C程序(使用hiredis C绑定)。Redis:当数据以换行符开始时的SET命令

这里是我的代码:

void insert(redisContext* c,char* buf){ 
     static redisReply *reply; 
     const char* hash="asdf"; 
     char* cmd=(char*)malloc((strlen("SET ")+strlen(hash)+strlen(" ")+CHUNKSIZE)*sizeof(char)); 

     //hash=getHash(buf); 
     memcpy(cmd,"SET ",(size_t)strlen("SET ")); 
     memcpy(cmd+strlen("SET "),hash,(size_t)strlen(hash)); 
     memcpy(cmd+strlen("SET ")+strlen(hash)," ",(size_t)strlen(" ")); 
     memcpy(cmd+strlen("SET ")+strlen(hash)+strlen(" "),buf,(size_t)CHUNKSIZE); 

     fwrite(cmd,strlen("SET ")+strlen(hash)+strlen(" ")+CHUNKSIZE,sizeof(char),stdout); 
     printf("\n\n\n\n\n\n"); 
     reply=(redisReply*)redisCommand(c,cmd); 
     freeReplyObject(reply); 

     free(cmd); 
} 

正如你所看到的,CMD的样子:SET asdf xxx,其中xxx为512个字节长(二进制数据)。

当二进制数据字符串以'\ n'开头时会出现问题。我不断收到错误(分段错误)。

任何人有任何想法?

非常感谢,

回答

1

我使用您发布的代码,并没有得到任何崩溃。 我的代码是:

#define CHUNKSIZE 512 
char asd[CHUNKSIZE]; 
memset(asd, 0, 512); 
asd[0] = '\n'; 
insert(c, asd); 

尝试用valgrind运行你的应用程序,可能会给你的崩溃之前,什么是错的一个更好的主意。

+0

非常感谢您的反馈意见。这显然是一些其他的错误。非常感激, – Eamorr 2011-12-19 14:30:00

1

hiredis文档:

当你需要通过二进制字符串安全的命令,可以使用%B符。用指针串起来,它需要一个字符串的长度的size_t参数:

reply = redisCommand(context, "SET foo %b", value, valuelen);