关于malloc_usable_size

最近想自己实现一个c版本的处理字符串的系列函数,为了得到heap上申请的char *的实际分配内存查阅了一些资料,最终发现malloc_usable_size符合我的要求,从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

真是完美啊,这个函数!于是乎我写出了下面这样的函数!

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

然后测试这两个函数:

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;

然后继续实现各种字符串处理的函数吧。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容