hiredis是redis官方提供的c客户端库。在读代码的过程中,发现了一个bug,记录一下。
hiredis里定义了一个上下文结构(struct redisContext),代码如下(deps/hiredis/hiredis.h):
https://github.com/antirez/hiredis/blob/master/hiredis.h
157
/*
Context for a connection to Redis
*/
158
typedef
struct
redisContext {
159
int
err;
/*
Error flags, 0 when there is no error
*/
160
char
errstr[
128
];
/*
String representation of error when applicable
*/
161
int
fd;
162
int
flags;
163
char
*obuf;
/*
Write buffer
*/
164
redisReader *reader;
/*
Protocol reader
*/
165
} redisContext;
针对这个结构,有一个对应的free function,代码如下(deps/hiredis/hiredis.c):
https://github.com/antirez/hiredis/blob/master/hiredis.c
1004
void
redisFree(redisContext *
c) {
1005
if
(c->fd >
0
)
1006
close(c->
fd);
1007
if
(c->obuf !=
NULL)
1008
sdsfree(c->
obuf);
1009
if
(c->reader !=
NULL)
1010
redisReaderFree(c->
reader);
1011
free(c);
1012
}
对照下,可以看到,定义中obuf成员使用的是char* ,而在释放操作时,却是按照sds结构(redis自己定义的类string数据结构)进行的释放。
如果再看下sdsfree的函数(deps/hiredis/sds.c),就能看到可能造成的灾难性后果:
https://github.com/antirez/hiredis/blob/master/sds.c
76
void
sdsfree(sds s) {
77
if
(s == NULL)
return
;
78
free(s-
sizeof
(
struct
sdshdr));
79
}
如上。在hiredis的github中,错误仍可以看到。
刚给redis DB邮件组发了封邮件,不知是否会被回复。

