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