檢查的使用也主要是對(duì)這些函數(shù)及其使用的內(nèi)存指針的追蹤
void * checkmem_malloc(size_t n, const char *fn, int line);
void checkmem_free(void* ptr, const char *fn, int line);
void * checkmem_realloc(void *ptr, size_t n, const char *fn, int line);
跟蹤就需要用到hash,由一個(gè)hash表來維護(hù)追蹤內(nèi)存的變化情況。
當(dāng)要查詢時(shí),打印hash表中需要的值。
比如
void *
checkmem_malloc(size_t n, const char *fn, int line)
{
void *ptr = NULL;
if ((n <= 0) || (fn == NULL) || (line <= 0)) {
printf("%s %d %s %d %ld\n\n", __func__, __LINE__,fn, line, n);
sleep(10);
}
if (checkmem_log == NULL) {
checkmem_log = checkmem_init();
if (checkmem_log == NULL) {
printf("%s %d fail to init checkmem_log handler\n\n", __func__, __LINE__);
return NULL;
}
}
ptr = ((void*)malloc(n));
if (ptr == NULL) {
printf("%s %d malloc error 0x%x\n\n", __func__, __LINE__,errno);
sleep(10);
} else {
checkmem_hash_add(checkmem_log, ptr, n, fn, line);
}
return ptr;
}
當(dāng)需要檢查內(nèi)存使用情況通過命令將其打印出來。
在打印出的所有沒有被釋放的內(nèi)存中,有些是屬于正常的,即程序一啟動(dòng)就會(huì)被分配,且一直不被釋放;另外還有一些內(nèi)存是不斷增加而不被釋放的,對(duì)于這些內(nèi)存就需要引起特別重視,它們很可能就是產(chǎn)生內(nèi)存泄露的地方。通過這一工具檢查,正常狀況應(yīng)該是經(jīng)過一段時(shí)間的運(yùn)行之后,內(nèi)存就保持到一個(gè)比較穩(wěn)定的狀態(tài),不再增加或減少。
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。