<p>This is a bit hypothetical and grossly simplified but...</p>

<p>Assume a program that will be calling functions written by third parties. These parties can be assumed to be non-hostile but can't be assumed to be "competent". Each function will take some arguments, have side effects and return a value. They have no state while they are not running.</p>

<p>The objective is to ensure they can't cause memory leaks by logging all mallocs (and the like) and then freeing everything after the function exits.</p>

<p>Is this possible? Is this practical?</p>

<p>p.s. The important part to me is ensuring that no allocations persist so ways to remove memory leaks without doing that are not useful to me.</p>

[{'answer_id': 50836, 'author': 'Mo.', 'author_id': 1870, 'author_profile': 'https://Stackoverflow.com/users/1870', 'pm_score': 1, 'selected': False, 'text': "<p>Can't you just force them to allocate all their memory on the stack? This way it would be garanteed to be freed after the function exits.</p>\n"}, {'answer_id': 50838, 'author': 'Yes - that Jake.', 'author_id': 5287, 'author_profile': 'https://Stackoverflow.com/users/5287', 'pm_score': 2, 'selected': False, 'text': '<p>A better solution than attempting to log mallocs might be to sandbox the functions when you call them—give them access to a fixed segment of memory and then free that segment when the function is done running.</p>\n\n<p>Unconfined, incompetent memory usage can be just as damaging as malicious code.</p>\n'}, {'answer_id': 50839, 'author': 'user4891', 'author_id': 4891, 'author_profile': 'https://Stackoverflow.com/users/4891', 'pm_score': 2, 'selected': False, 'text': '<p>You could run the third party functions in a separate process and close the process when you are done using the library.</p>\n'}, {'answer_id': 50842, 'author': 'Jason Cohen', 'author_id': 4926, 'author_profile': 'https://Stackoverflow.com/users/4926', 'pm_score': 2, 'selected': False, 'text': '<p>First, you have to provide the entrypoints for <code>malloc()</code> and <code>free()</code> and friends.  Because this code is compiled already (right?) you can\'t depend on <code>#define</code> to redirect.</p>\n\n<p>Then you can implement these in the obvious way and log that they came from a certain module by linking those routines to those modules.</p>\n\n<p>The fastest way involves <em>no logging at all.</em>  If the amount of memory they use is bounded, why not pre-allocate all the "heap" they\'ll ever need and write an allocator out of that?  Then when it\'s done, free the entire "heap" and you\'re done!  You could extend this idea to multiple heaps if it\'s more complex that that.</p>\n\n<p>If you really do need to "log" and not make your own allocator, here\'s some ideas. One, use a hash table with pointers and internal chaining.  Another would be to allocate extra space in front of every block and put your own structure there containing, say, an index into your "log table," then keep a free-list of log table entries (as a stack so getting a free one or putting a free one back is O(1)).  This takes more memory but should be fast.</p>\n\n<p>Is it practical?  I think it is, so long as the speed-hit is acceptable.</p>\n'}, {'answer_id': 50848, 'author': '17 of 26', 'author_id': 2284, 'author_profile': 'https://Stackoverflow.com/users/2284', 'pm_score': 0, 'selected': False, 'text': "<p>Since you're worried about memory leaks and talking about malloc/free, I assume you're in C.  I'm also assuming based on your question that you do not have access to the source code of the third party library.</p>\n\n<p>The only thing I can think of is to examine memory consumption of your app before &amp; after the call, log error messages if they're different and convince the third party vendor to fix any leaks you find.</p>\n"}, {'answer_id': 50861, 'author': 'DGentry', 'author_id': 4761, 'author_profile': 'https://Stackoverflow.com/users/4761', 'pm_score': 4, 'selected': True, 'text': "<p>You don't specify the operating system or environment, this answer assumes Linux, glibc, and C.</p>\n\n<p>You can set __malloc_hook, __free_hook, and __realloc_hook to point to functions which will be called from malloc(), realloc(), and free() respectively. There is a __malloc_hook manpage showing the prototypes. You can add track allocations in these hooks, then return to let glibc handle the memory allocation/deallocation.</p>\n\n<p>It sounds like you want to free any live allocations when the third-party function returns. There are ways to have gcc automatically insert calls at every function entrance and exit using -finstrument-functions, but I think that would be inelegant for what you are trying to do. Can you have your own code call a function in your memory-tracking library after calling one of these third-party functions? You could then check if there are any allocations which the third-party function did not already free.</p>\n"}, {'answer_id': 50877, 'author': 'Steve Wranovsky', 'author_id': 3429, 'author_profile': 'https://Stackoverflow.com/users/3429', 'pm_score': 1, 'selected': False, 'text': '<p>In the past I wrote a software library in C that had a memory management subsystem that contained the ability to log allocations and frees, and to manually match each allocation and free.  This was of some use when attempting to find memory leaks, but it was difficult and time consuming to use.  The number of logs was overwhelming, and it took an extensive amount of time to understand the logs.  </p>\n\n<p>That being said, if your third party library has extensive allocations, its more then likely impractical to track this via logging.  If you\'re running in a Windows environment, I would suggest using a tool such as Purify[1] or BoundsChecker[2] that should be able to detect leaks in your third party libraries.  The investment in the tool should pay for itself in time saved.</p>\n\n<p>[1]: <a href="http://www-01.ibm.com/software/awdtools/purify/" rel="nofollow noreferrer">http://www-01.ibm.com/software/awdtools/purify/</a> Purify</p>\n\n<p>[2]: <a href="http://www.compuware.com/products/devpartner/visualc.htm" rel="nofollow noreferrer">http://www.compuware.com/products/devpartner/visualc.htm</a> BoundsChecker</p>\n'}, {'answer_id': 220631, 'author': 'Jonathan Leffler', 'author_id': 15168, 'author_profile': 'https://Stackoverflow.com/users/15168', 'pm_score': 0, 'selected': False, 'text': '<p>If you have money to spare, then consider using Purify to track issues.  It works wonders, and does not require source code or recompilation.  There are also other debugging malloc libraries available that are cheaper.  Electric Fence is one name I recall.  That said, the debugging hooks mentioned by Denton Gentry seem interesting too.</p>\n'}, {'answer_id': 220704, 'author': 'Mitch Haile', 'author_id': 28807, 'author_profile': 'https://Stackoverflow.com/users/28807', 'pm_score': 0, 'selected': False, 'text': "<p>If you're too poor for Purify, try Valgrind.  It it a lot better than it was 6 years ago and a lot easier to dive into than Purify.</p>\n"}, {'answer_id': 938940, 'author': 'RandomNickName42', 'author_id': 67819, 'author_profile': 'https://Stackoverflow.com/users/67819', 'pm_score': 0, 'selected': False, 'text': '<p>Microsoft Windows provides (use SUA if you need a POSIX), quite possibly, the most advanced heap+(other api known to use the heap) infrastructure of any shipping OS today.</p>\n\n<p>the __malloc() debug hooks and the associated CRT debug interfaces are nice for cases where you have the source code to the tests, however they can often miss allocations by standard libraries or other code which is linked.  This is expected as they are the Visual Studio heap debugging infrastructure.</p>\n\n<p><strong><a href="http://technet.microsoft.com/en-us/library/cc738763(WS.10).aspx" rel="nofollow noreferrer">gflags</a></strong> is a very comprehensive and detailed set of debuging capabilities which has been included with Windows for many years. Having advanced functionality for source and binary only use cases (as it is the OS heap debugging infrastructure).</p>\n\n<p>It can log full stack traces (repaginating symbolic information in a post-process operation), of all heap users, for all heap modifying entrypoint\'s, serially if needed.  Also, it may modify the heap with pathalogical cases which may align the allocation of data such that the page protection offered by the VM system is optimally assigned (i.e. allocate your requested heap block at the end of a page, so even a singele byte overflow is detected at the time of the overflow.</p>\n\n<p>umdh is a tool which can help assess the status at various checkpoints, however the data is continually accumulated during the execution of the target o it is not a simple checkpointing debug stop in the traditional context.  Also, <em>WARNING</em>, Last I checked at least, the total size of the circular buffer which store\'s the stack information, for each request is somewhat small (64k entries (entries+stack)), so you may need to dump rapidly for heavy heap users.  There are other ways to access this data but umdh is fairly simple.</p>\n\n<p><strong>NOTE</strong> there are 2 modes;</p>\n\n<ol>\n<li>MODE 1, umdh {-p:Process-id|-pn:ProcessName} [-f:Filename] [-g]</li>\n<li><p>MODE 2, umdh [-d] {File1} [File2] [-f:Filename]</p>\n\n<p><em>I do not know what insanity gripped the developer who chose to alternate between -p:foo argument specifier\'s and naked ordering of argument\'s but it can get a little confusing.</em></p></li>\n</ol>\n\n<p>The debugging sdk works with a number of other tools, <a href="http://technet.microsoft.com/en-us/library/cc757686(WS.10).aspx" rel="nofollow noreferrer">memsnap</a> is a tool which apparently focuses on memory leask and such, but I have not used it, your milage may vary.</p>\n\n<p>Execute gflags with no arguments for the UI mode, +arg\'s and /args are <em>different</em> "modes" of use also.</p>\n'}, {'answer_id': 60252131, 'author': 'Ruslan', 'author_id': 673852, 'author_profile': 'https://Stackoverflow.com/users/673852', 'pm_score': 0, 'selected': False, 'text': '<p>On Linux I\'ve successfully used <a href="http://man7.org/linux/man-pages/man3/mtrace.3.html" rel="nofollow noreferrer"><code>mtrace(3)</code></a> to log allocations and freeings. Its usage is as simple as</p>\n\n<ol>\n<li>Modify your program to call <code>mtrace()</code> when you need to begin tracing (e.g. at the top of <code>main()</code>),</li>\n<li>Set environment variable <code>MALLOC_TRACE</code> to the file path where the trace should be saved and run the program.</li>\n</ol>\n\n<p>After that the output file will contain something like this (excerpt from the middle to show a failed allocation):</p>\n\n<pre><code>@ /usr/lib/tls/libnvidia-tls.so.390.116:[0xf44b795c] + 0x99e5e20 0x49\n@ /opt/gcc-7/lib/libstdc++.so.6:(_ZdlPv+0x18)[0xf6a80f78] - 0x99beba0\n@ /usr/lib/tls/libnvidia-tls.so.390.116:[0xf44b795c] + 0x9a23ec0 0x10\n@ /opt/gcc-7/lib/libstdc++.so.6:(_ZdlPv+0x18)[0xf6a80f78] - 0x9a23ec0\n@ /opt/Xorg/lib/video-libs/libGL.so.1:[0xf668ee49] + 0x99c67c0 0x8\n@ /opt/Xorg/lib/video-libs/libGL.so.1:[0xf668f14f] - 0x99c67c0\n@ /opt/Xorg/lib/video-libs/libGL.so.1:[0xf668ee49] + (nil) 0x30000000\n@ /lib/libc.so.6:[0xf677f8eb] + 0x99c21f0 0x158\n@ /lib/libc.so.6:(_IO_file_doallocate+0x91)[0xf677ee61] + 0xbfb00480 0x400\n@ /lib/libc.so.6:(_IO_setb+0x59)[0xf678d7f9] - 0xbfb00480\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/50829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1343/']