Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use malloc_stats in C program on Linux

Tags:

c

linux

memory

gdb

I was trying to print the memory allocation statistics by calling malloc_stats() in my C program which is running on Linux. However it does not provide any outputs. According to the manpage of malloc_stats() the information is sent to the standard error. So how can I redirect the malloc_stats() info to a log file for my program?

I also tried calling malloc_stats() in gdb however that does not give me the proper info either:

(gdb) call malloc_stats()
[Switching to Thread 182928084768 (LWP 11950)]
$2 = -1759135936
(gdb)

What is wrong with my gdb?

like image 556
leilai Avatar asked Apr 23 '26 06:04

leilai


1 Answers

You can't change where the malloc_stats output goes, you'll need to redirect stderr yourself (e.g. use freopen) if you want that somewhere else.

If you have a recent-enough glibc (>= 2.10), you can use malloc_info(3) which takes a FILE* as one of its parameters (and outputs XML). Combine that with open_memstream(3) and you could get that in a memory buffer.

(I don't know what's wrong with your gdb, mine prints the stats just fine - GDB 7.3.1, glibc 7.15.)

like image 132
Mat Avatar answered Apr 25 '26 18:04

Mat