[LLVMdev] getElapsedWallTime unnecessary heap allocation and memory leak

Alexey Samsonov samsonov at google.com
Wed Mar 19 06:46:00 PDT 2014


Hi Bryan,

On Wed, Mar 19, 2014 at 5:17 PM, Bryan Keiren <
bryan.keiren at guerrilla-games.com> wrote:

>  In the file \lib\Support\Process.cpp on line 60, it seems as though an
> unnecessary heap allocation and memory leak occurs.
>
>
>
> This is the offending code:
>
>
>
> *static TimeValue getElapsedWallTime() {*
>
> *  static TimeValue &StartTime = *new TimeValue(TimeValue::now());*
>
> *  return TimeValue::now() - StartTime;*
>
> *}*
>
>
>
> The issue is that the *StartTime* variable's value is allocated on the
> heap, after which a **reference** to it is stored (not the pointer
> itself). This means that the allocated memory is actually never properly
> de-allocated.
>

What is the difference between storing a pointer and a reference here?


>  Granted, the memory leak is small but if anyone attempts to write memory
> leak-free software while including LLVM code, this will be an issue (as it
> currently is for our company).
>
>
>
>
>
> Is there anyone who knows why exactly this was implemented the way it
> currently is implemented? It seems rather unnecessary to be implemented
> with this complexity when a simpler implementation would work as well:
>
>
>
> *static TimeValue getElapsedWallTime() {*
>
> *  static TimeValue TimeValue(TimeValue::now());*
>
> *  return TimeValue::now() - StartTime;*
>
> *}*
>

Function-local static variables might be dangerous and lead to
destruction-order problems. For example, if a program calls
getElapsedWallTime() at destruction time (after main() exits), then static
variable TimeValue might already
be destroyed/deallocated. Memory pointed to by StartValue will most likely
be considered as "reachable" until the end of the program, and shouldn't
cause error reports by leak detectors, such as LeakSanitizer, for instance (
http://clang.llvm.org/docs/LeakSanitizer.html)


>
>
> _______________________________________________
> LLVM Developers mailing list
> LLVMdev at cs.uiuc.edu         http://llvm.cs.uiuc.edu
> http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev
>
>


-- 
Alexey Samsonov, MSK
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20140319/77e5df98/attachment.html>


More information about the llvm-dev mailing list