I am trying to create wrapper functions for free
and malloc
in C to help notify me of memory leaks. Does anyone know how to declare these functions so when I call malloc()
and free()
it will call my custom functions and not the standards lib functions?
相关问题
- Multiple sockets for clients to connect to
- What uses more memory in c++? An 2 ints or 2 funct
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Achieving the equivalent of a variable-length (loc
If you are only talk about memory that you have under control, i.e. that you malloc and free on your own, you can take a look on rmdebug. Probably it is what you are going to write anyway, so you can save sometime. It has a very liberal licence, if that should be important for you.
I personally use it in a project, to look for memory leaks, the nice things is that it is much faster then valgrind, however it isn't that powerful so you don't get the full calling stack.
Sorry for reopening a 7 years old post.
In my case I needed to wrap memalign/aligned_malloc under malloc. After trying other solutions I ended up implementing the one listed below. It seems to be working fine.
mymalloc.c.
If your goal is to eliminate memory leaks, an easier, less intrusive way is to use a tool like Valgrind (free) or Purify (costly).
You can do wrapper and "overwrite" function with LD_PRELOAD - similarly to example shown earlier.
But I recommend to do this "slightly" smarter, I mean calling dlsym once.
example I've found here: http://www.jayconrod.com/cgi/view_post.py?23 post by Jay Conrod.
But what I've found really cool at this page is that: GNU linker provides a useful option, --wrap . When I check "man ld" there is following example:
I agree with them that's "trivial example" :). Even dlsym is not needed.
Let, me cite one more part of my "man ld" page:
I hope, description is complete and shows how to use those things.
In C, the method I used was similar to:
This allowed me to detect the line and file of where the memory was allocated without too much difficulty. It should be cross-platform, but will encounter problems if the macro is already defined (which should only be the case if you are using another memory leak detector.)
If you want to implement the same in C++, the procedure is a bit more complex but uses the same trick.
If you define your own functions for malloc() and free() and explicitly link that with your applications, your functions should be used in preference to those in the library.
However, your function called 'malloc' cannot then call the library malloc function, because in 'c' there's no concept of separate namespaces. In other words, you'd have to implement the internals of malloc and free yourself.
Another approach would be to write functions my_malloc() and my_free(), which call the standard library ones. This would mean that any code calling malloc would have to be changed to call your my_xxx functions.