On 4.05.2019 14:14, James Kuyper wrote:
> On 5/4/19 1:34 AM, Paavo Helde wrote:
>> On 3.05.2019 23:22, Thiago Adams wrote:
> ...
>>> Just add some memory leak detector and you will be disciplined.
>>> It is very easy to create one and use in debug.
>>
>> Easy in toy programs, you mean. It only catches the leaks which are
>> triggered by the tests for which you have time to run through in this
>> mode. And it produces false alarms for long-lived static data
>> structures.
>
> What algorithm would a memory leak detector use that would confuse
> "long-lived static data structures" for allocated memory?
The one posted by grandparent which just redefines malloc/new and
instruments each call in the same way.
>
> The only things I would bother calling proper "memory leak detectors"
> are integrated into the memory allocation and deallocation routines, and
> as such always know precisely which pieces of memory are dynamically
> allocated, and which are not (or at least, in the event of heap
> corruption, are no more confused than those routines themselves would be).
The static data structures I talked about are allocated dynamically.
Rough example:
static std::map<std::string, std::shared_ptr<Module>> gTheGlobalMap;
int main() {
InitGlobalMap(gTheGlobalMap); // many dynamic allocations
RegisterPlugins(gTheGlobalMap); // many dynamic allocations
while (!terminated) {
ServiceRequests();
}
}
As long as the global map contents exist these are considered as
"leaked" by such a leak detection tool. In the program end it might get
deleted so it might make the picture clearer, but to be honest there
would no point in destroying such a global map, as it just makes the
program shutdown slower. So some programs and some third-party libraries
may skip the deletion step, causing a huge avalanche of false alarms
where real leaks are lost in. Been there, seen that.
Alas, the leaks may appear and cause problems long before the program
end. And in some cases the leaks are not leaks "by definition", but just
some hierarchic data structure which tend to grow indefinitely, eating
up all the memory and crashing the program all the same, not caring
about if somebody defines them as leaks or not. Such offenders might be
even nicely destroyed at the program end, making it impossible to
discover at the program end. Been there, seen that.
Yes, you can instrument the memory allocation calls, and you can detect
leaks that way, but in large and complicated programs it would not be so
simple and not so easy (hint: a statistic analysis of allocations' size
distribution might appear useful).