- redis中sdshdr结构的内存总是整体进行分配和扩充,因此在进行free的时候只需要直接以sdshdr指针为参数调用free即可释放内存
struct sdshdr {
// buf 中已占用空间的长度
int len;
// buf 中剩余可用空间的长度
int free;
// 数据空间
char buf[];
};
-
sds结构中一个比较trick的地方:通过buf指针获取到结构体起始位置
在C99中,当结构体的成员变量为一个可变数组时,sizeof操作的结果中不包含可变数组所占的空间
C99 introduced a means to define the "struct hack": it's now called "flexible array member" and before it is allocated memory, its size is 0.
static inline size_t sdslen(const sds s) {
//传入参数s为指向buf的指针,因此需要首先找到结构体开始的位置,然后才能通过结构体的开始位置获取到结构体中的len成员变量
//注意一个非常trick的地方sizeof(sdshdr)等于len和free所占的空间,buf是一个空数组,在进行内存分配前不占用任何的空间
//C99 introduced a means to define the "struct hack": it's now called "flexible array member" and before it is allocated memory, its size is 0.
struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
return sh->len;
}