Blender  V2.93
leak_detector.cc
Go to the documentation of this file.
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  */
16 
21 #include <cstdio> /* Needed for `printf` on WIN32/APPLE. */
22 #include <cstdlib>
23 
24 #include "MEM_guardedalloc.h"
25 #include "mallocn_intern.h"
26 
27 bool leak_detector_has_run = false;
29  "Freeing memory after the leak detector has run. This can happen when using "
30  "static variables in C++ that are defined outside of functions. To fix this "
31  "error, use the 'construct on first use' idiom.";
32 
33 namespace {
34 
35 bool fail_on_memleak = false;
36 bool ignore_memleak = false;
37 
38 class MemLeakPrinter {
39  public:
40  ~MemLeakPrinter()
41  {
42  if (ignore_memleak) {
43  return;
44  }
45  leak_detector_has_run = true;
46  const uint leaked_blocks = MEM_get_memory_blocks_in_use();
47  if (leaked_blocks == 0) {
48  return;
49  }
50  const size_t mem_in_use = MEM_get_memory_in_use();
51  printf("Error: Not freed memory blocks: %u, total unfreed memory %f MB\n",
52  leaked_blocks,
53  (double)mem_in_use / 1024 / 1024);
55 
56  if (fail_on_memleak) {
57  /* There are many other ways to change the exit code to failure here:
58  * - Make the destructor noexcept(false) and throw an exception.
59  * - Call exit(EXIT_FAILURE).
60  * - Call terminate().
61  */
62  abort();
63  }
64  }
65 };
66 } // namespace
67 
69 {
79  static MemLeakPrinter printer;
80 }
81 
83 {
84  ignore_memleak = !enabled;
85 }
86 
88 {
89  fail_on_memleak = true;
90 }
unsigned int uint
Definition: BLI_sys_types.h:83
Read Guarded memory(de)allocation.
bool enabled
void MEM_use_memleak_detection(bool enabled)
void MEM_enable_fail_on_memleak(void)
bool leak_detector_has_run
void MEM_init_memleak_detection(void)
char free_after_leak_detection_message[]
size_t(* MEM_get_memory_in_use)(void)
Definition: mallocn.c:59
unsigned int(* MEM_get_memory_blocks_in_use)(void)
Definition: mallocn.c:60
void(* MEM_printmemlist)(void)
Definition: mallocn.c:53
static size_t mem_in_use