3 ms·
So write your own allocator... EDIT: That might sound snarky, it's not meant to be. I just mean that you can do something like this: https://gist.github.com/j
by joeld42 11y ago
So write your own allocator...
EDIT: That might sound snarky, it's not meant to be. I just mean that you can do something like this:
https://gist.github.com/joeld42/74f67cde97a789467a2f681961b89c27 https://gist.github.com/joeld42/74f67cde97a789467a2f681961b8...
people complain about C's memory manager, but really it's one of the most flexible out there because you can do stuff like this. Well written C libraries will provide hooks to use a custom allocator if needed.
- jandrese 11y agoYou're missing the point though. Unless you can take over the world (and the C stdlib!) with this allocator it is of limited use. You have to rewrite everything to use it to get any value out of it. So it's great for your own internal code, but of pretty limited value once you start pulling in libraries.
- joeld42 11y agoNo, I've plugged in custom allocators into codebases that had millions of lines of C (and even C++). Very few functions in the C stdlib allocate memory. Most that do (like strdup) are convenience wrappers. Most decent 3rd party libraries will allow you to plug in your own allocators, and if they don't, they should. Typically you do something like #define LIBFOO_ALLOC my_alloc before including things, or they have some kind of function like setAllocator().. For example, here's how to do it for Freetype (a pretty large 3rd party library). http://www.freetype.org/freetype2/docs/design/design-4.html http://www.freetype.org/freetype2/docs/design/design-4.html If a 3rd party library didn't let me do this, I would probably refuse to use it (or patch it). And you can always search/replace malloc and free if you're using some 3rd party code that doesn't do that. It really doesn't take that long. Also, malloc and free are specified to be weakly linked, so you can implement your own and replace the cstdlib ones even if you don't have the source available. This isn't a great option, but it works, especially if you're just using it for a diagnostic build. If you're talking about C++, that's yet another thing the STL screwed up. You can usually find ways to work around it but yeah, it's a bigger problem.