What is the purpose of malloc hooks?
What exactly is 开发者_StackOverflow社区the purpose of using malloc hooks? And I've read it's used in memory-profiling, etc. but never really understood how.
Well, if you can hook into the behaviour of allocation functions, then you can track memory allocations for profiling and debugging.
The GCC documentation on malloc hooks has a nice little example demonstrating adding debug output every time the allocation functions are invoked.
I'm not really sure what else to tell you... is that not reason enough?
One very simple example: suppose you know that memory allocated by allocation number N (N is the same in each run) is always leaked in your code. You can set a hook and inside put a breakpoint on condition "allocation number equals N". Once that breakpoint is hit you examine the call stack and find why exactly that memory is leaked later.
It's a simple way to make sure that your application is not leaking memory. This can be very important if it has to run for a long time in an environment with limited memory. You can use it while testing, and turn it off in the release version.
They can also be used to replace the allocator altogether e.g. with umem or boehm-gc either for testing or because it is more efficient for a particular application.
精彩评论