关于malloc_usable_size

malloc_usable_size函数的作用 ----- Linux下获取malloc实际分配的内存大小

http://www.man7.org/linux/man-pages/man3/malloc_usable_size.3.html 可以得到malloc_usable_size的解释:

malloc_usable_size - obtain size of block of memory allocated from heap

使用的函数原型如下:

#include <malloc.h>
size_t malloc_usable_size(void *_ptr)

使用如下:

demo1: 

void malloc_test()
{
    char *array = (char *)malloc(1 * sizeof(char));
    int ntem = malloc_usable_size(array);
    printf("ntem: %d\n", ntem);
    free(array);
}

demo2:  

typedef char * cstring;

#define NULL_PTR_ERROR \
printf("allocate memory error.\n" ); \
exit(1);

cstring
new_cstring_with_size(size_t n) {
    cstring s = malloc((n + 1) * sizeof(char));
    memset(s, 0, n + 1);
    if(!s) {
        printf("new_cstring_with_size: ");
        NULL_PTR_ERROR
    }
    return s;
}

size_t
cstring_size(cstring s) {
    // 实际上有这么多空间可以用
    return malloc_usable_size(s) - 1;
}

 测试demo2两个函数: 

cstring s = new_cstring_with_size(128);
size_t t = cstring_size(s);
printf("%zu\n", t);

然后结果就出现"异常"!哈哈,喜闻乐见!输出一直是135,而不是127。纳闷归纳闷,问题还是得解决,所以又开始了查阅资料,最终在这里http://manpages.ubuntu.com/manpages/precise/man3/mallopt.3.html 找到了解释:

malloc_usable_size() returns the number of bytes available in the dynamically allocated buffer ptr, which may be greater than the requested size (but is guaranteed to be at least as large, if the request was successful). Typically, you should store the requested allocation size rather than use this function.

 也就是说函数的返回值是大于等于你申请的size的。哎!根据typically后的说法,只能设计结构体保存char *的length:

typedef struct {
    size_t size; // 比实际分配的内存少一个字节,即最后一个字节'\0'
    char *str;
}cstring_data;

参考:

链接1:       Linux下获取malloc实际分配的内存大小_花一样的阿衰的博客-CSDN博客_获取malloc大小
链接2:https://www.jianshu.com/p/b55cd79e719e
 

阅读终点,创作起航,您可以撰写心得或摘录文章要点写篇博文。去创作
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_27898413

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值