mallinfo, 打印堆栈, malloc钩子, mtrace()

本文介绍如何使用mallinfo获取当前进程的内存使用情况,通过backtrace打印堆栈信息来追踪内存分配的位置,并利用malloc钩子函数来扩展malloc和free的行为。此外还介绍了如何使用mtrace检查内存泄漏。

mallinfo, 打印堆栈, malloc钩子, mtrace()



一:获得即时内存状态:

void getMemStatus()
{
    struct mallinfo info = mallinfo ();
    printf("arena = %d/n", info.arena);
    printf("ordblks = %d/n", info.ordblks);
    printf("smblks = %d/n", info.smblks);
    printf("hblks = %d/n", info.hblks);
    printf("hblkhd = %d/n", info.hblkhd);
    printf("usmblks = %d/n", info.usmblks);
    printf("fsmblks = %d/n", info.fsmblks);
    printf("uordblks = %d/n", info.uordblks);
    printf("fordblks = %d/n", info.fordblks);
    printf("keepcost = %d/n", info.keepcost);
}

Usage:

#include <malloc.h>
 
struct mallinfo [Data Type]
This structure type is used to return information about the dynamic memory allocator.
It contains the following members:
int arena
    This is the total size of memory allocated with sbrk by malloc, in bytes.
int ordblks
    This is the number of chunks not in use. (The memory allocator internally gets chunks of memory from the operating system, and then carves them up to satisfy individual malloc requests; see Section 3.2.2.6 [Eciency Considerations for malloc], page 36.)
int smblks
    This field is unused.
int hblks
    This is the total number of chunks allocated with mmap.
int hblkhd
    This is the total size of memory allocated with mmap, in bytes.
int usmblks
    This field is unused.
int fsmblks
    This field is unused.
int uordblks
    This is the total size of memory occupied by chunks handed out by malloc.
int fordblks
    This is the total size of memory occupied by free (not in use) chunks.
int keepcost
    This is the size of the top-most releasable chunk that normally borders the end of the heap (i.e., the high end of the virtual address space''s data segment).
struct mallinfo mallinfo (void) [Function]
    This function returns information about the current dynamic memory usage in a structure of type struct mallinfo.


二:打印堆栈:

     #include <execinfo.h>

     #include <stdio.h>

     #include <stdlib.h>

   

     /* Obtain a backtrace and print it to stdout. */

     void print_trace (void)

     {

       void *array[10];

       size_t size;

       size_t i;

   

       size = backtrace (array, 10);

       printf ("Obtained %zd stack frames./n", size);

   

       for (i = 0; i < size; i++)

          printf ("%p /n",  array [i]);

     }

   

     /* A dummy function to make the backtrace more interesting. */

     void dummy_function (void)

     {

       print_trace ();

     }

   

     int main (void)

     {

       dummy_function ();

       return 0;

     }

三:malloc钩子函数

static void* (* old_malloc_hook) (size_t,const void *);
static void (* old_free_hook)(void *,const void *);
static void my_init_hook(void);
static void* my_malloc_hook(size_t,const void*);
static void  my_free_hook(void*,const void *);

static void my_init_hook(void)
{
    old_malloc_hook = __malloc_hook;
    old_free_hook = __free_hook;
    __malloc_hook = my_malloc_hook;
    __free_hook = my_free_hook;
}


static void* my_malloc_hook(size_t size,const void *caller)
{
    void *result;
//    print_trace();
    __malloc_hook = old_malloc_hook;
    result = malloc(size);
    old_malloc_hook = __malloc_hook;
    PHONE_DEBUG_PRINT("/n@@@ %p + %p 0x%x/n",caller,result,(unsigned long int)size);
    __malloc_hook = my_malloc_hook;

    return result;
}

static void my_free_hook(void *ptr,const void *caller)
{
    __free_hook = old_free_hook;
    free(ptr);
    old_free_hook = __free_hook;
    PHONE_DEBUG_PRINT("/n@@@ %p - %p/n",caller,ptr);
    __free_hook = my_free_hook;
}

just need call my_init_hook() at the check point.

四:check memory leak

 

想要跟踪的时候用mtrace。
 
停止跟踪可以使用muntrace.
 
内存泄漏检查方法(for Linux) :

如果你更想读原始文档, 请参考glibc info的"Allocation Debugging"
一章 (执行info libc);
glibc提供了一个检查内存泄漏的方法, 前提是你的程序使用glibc的标准函数
分配内存(如malloc, alloc...):

1. 在需要内存泄漏检查的代码的开始调用void mtrace(void) (在mcheck.h中
? 有声明). mtrace为malloc等函数安装hook, 用于记录内存分配信息.
在需要内存泄漏检查的代码的结束调用void muntrace(void).
注意: 一般情况下不要调用muntrace, 而让程序自然结束. 因为可能有些
释放内存代码要到muntrace之后才运行.

2. 用debug模式编译被检查代码(-g或-ggdb)

3. 设置环境变量MALLOC_TRACE为一文件名, 这一文件将存有内存分配信息.

4. 运行被检查程序, 直至结束或muntrace被调用.

5. 用mtrace命令解析内存分配Log文件($MALLOC_TRACE)
(mtrace foo $MALLOC_TRACE, where foo is the executible name)
如果有内存泄漏, mtrace会输出分配泄漏
内存的代码位置,以及分配数量.


其他东西

1. 可以将mtrace, muntrace放入信号处理函数(USR1, USR2), 以动态地进行
内存泄漏检查控制.

2. mtrace是个perl代码, 如果你对符号地址与代码文本的转换感兴趣, 可以
读一下.

3. again, 尽量不要用muntrace()


 

1 #include <mcheck.h>
      2
      3 int main()
      4 {
      5 mtrace();
      6 malloc(10);
      7 malloc(16);
      8 return 0;
      9 }

$gcc -g a.c #记得编译带-g调试选项
$export MALLOC_TRACE=a.log
$./a.out
$unset MALLOC_TRACE #记得执行完后unset变量,否则可能运行其他命令可能覆盖log
$mtrace a.out a.log
Memory not freed:
-----------------
   Address     Size     Caller
0x09b08378      0xa  at /XXX/a.c:6
0x09b08388     0x10  at /XXX/a.c:7

可以看到,会显示未释放动态空间的代码具体位置.

### mallinfo 各字段含义详解 `mallinfo` 是 GNU C 库中提供的一种接口,用于获取 `malloc` 分配器的内存使用统计信息。它返回一个结构体 `struct mallinfo`,其中包含多个字段,分别反映了堆内存的不同方面状态。以下是各主要字段的详细解释: - **int arena** 表示当前分配给堆的总空间大小(以字节为单位)。这个值包括已使用的块和空闲块。它是通过 `sbrk` 或 `mmap` 扩展得到的整个堆区域的大小。 - **int ordblks** 表示当前堆中处于空闲状态的块的数量。这些块尚未被分配,但已经被 `malloc` 管理器保留下来,供后续请求使用。 - **int smblks** 表示“小块”(small blocks)的数量。这是指在某些实现中,小于某个阈值的小型空闲块的总数。不过该字段在现代 glibc 实现中已被弃用,通常返回零。 - **int hblks** 表示通过 `mmap` 分配的共享内存或私有映射段的数量。这些段通常是用于大对象分配的独立虚拟内存区域。 - **int hblkhd** 表示通过 `mmap` 分配的内存总量(以字节为单位),这部分内存不经过主堆管理器,而是由 `mmap` 直接从操作系统获取[^1]。 - **int usmblks** 表示当前正在使用的最大内存块大小。在一些系统中,它可能未被实现,始终返回零。 - **int fsmblks** 表示所有小型空闲块的总大小。与 `smblks` 类似,该字段也较少使用,且在某些版本中可能无效。 - **int uordblks** 表示已分配给用户使用的内存量(以字节为单位),即当前所有活跃块的总和。这不包括空闲块和其他开销。 - **int fordblks** 表示当前所有空闲块的总大小。这些块可以被后续的 `malloc` 请求复用。 - **int keepcost** 表示最近一次收缩操作后保留的空闲块大小。它用于估计下一次收缩操作的成本,帮助优化内存释放策略。 ### 示例代码:使用 `mallinfo` ```c #include <malloc.h> #include <stdio.h> int main() { struct mallinfo mi = mallinfo(); printf("Total non-mmapped space allocated (arena): %d\n", mi.arena); printf("Number of free chunks (ordblks): %d\n", mi.ordblks); printf("Space allocated in mmap regions (hblkhd): %d\n", mi.hblkhd); printf("Space used (uordblks): %d\n", mi.uordblks); printf("Space free (fordblks): %d\n", mi.fordblks); return 0; } ``` 上述程序展示了如何获取并打印 `mallinfo` 中的部分关键字段。这些数据有助于分析程序运行期间的内存消耗情况,特别是在调试内存泄漏或优化性能时非常有用。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值