關(guān)于malloc_usable_size

最近想自己實現(xiàn)一個c版本的處理字符串的系列函數(shù),為了得到heap上申請的char *的實際分配內(nèi)存查閱了一些資料,最終發(fā)現(xiàn)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

真是完美啊,這個函數(shù)!于是乎我寫出了下面這樣的函數(shù)!

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

然后測試這兩個函數(shù):

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

然后結(jié)果就出現(xiàn)"異常"!哈哈,喜聞樂見!輸出一直是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.

也就是說函數(shù)的返回值是大于等于你申請的size的。哎!根據(jù)typically后的說法,只能設(shè)計結(jié)構(gòu)體保存char *的length:

typedef struct {
    size_t size; // 比實際分配的內(nèi)存少一個字節(jié),即最后一個字節(jié)'\0'
    char *str;
}cstring_data;

然后繼續(xù)實現(xiàn)各種字符串處理的函數(shù)吧。。。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容