关于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
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值