redis sds学习

  • 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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值