Reporting Memory Leaks in Strategy Tester – library MetaTrader 5

The strategy tester does not report any memory leaks of MQL5 applications like expert advisors, scripts or indicators. And such memory leaks can occur by using the  new operator in your MQL5 code and forgetting to free the occupied memory later in your code by calling the  delete  operator. For example in complex programs with many classes and data collections the  obligatory usage of the  delete  operator can be overseen very easily, and it can be difficult to trace such problems.

In my opinion the strategy tester should not only be used to develop a coherent trading logic, but also to detect software-related problems. Especially for finding memory leaks. The earlier such problems can be found and fixed the better.

Therefore here is presented an include file with name “checker_for_memory_leaks”. Dominik Egert made a significant contribution to this file; please look at https://www.mql5.com/en/forum/438987

This header file can be used for Expert Advisors, Scripts and Custom Indicators and should be included at the very beginning of the code. The purpose is to monitor eventually occurring memory leaks during the testing of your application in the strategy tester. Otherwise there is no need to change the actual code. In the header file the operators  new  and  delete  are ‘bent’ to allow an indication of the leaks that occur eventually. After having thoroughly tested your application and fixed all memory leaks you simply can uncomment/remove the   #include <checker_for_memory_leaks.mqh>   statement in your program.

Alternative:  Demo_FileWrite - script MetaTrader 5

As an example here a very simple script named  “MemoryLeak.mq5”  using this header is presented:

#include <checker_for_memory_leaks.mqh>

//+------------------------------------------------------------------+
//| Simple class CA without any content                              |
//+------------------------------------------------------------------+
class CA {};
void OnStart()
  {
   CA *a;
   a = new CA;
   if(a == NULL)
     {
      Print("NULL Pointer!");
      return;
     }
// 'forget' to call the delete operator'
// delete a;
  }
//+------------------------------------------------------------------+

The output:

2023.08.12 11:45:26.072 MemoryLeak (.DE40Cash,M15)      -- Resume Memory Leaks --
2023.08.12 11:45:26.072 MemoryLeak (.DE40Cash,M15)      1 undeleted objects left
2023.08.12 11:45:26.072 MemoryLeak (.DE40Cash,M15)        - File MemoryLeak.mq5 Line 10
2023.08.12 11:45:26.072 MemoryLeak (.DE40Cash,M15)      -- End Resume --

You can see in which file and which line the memory has been allocated. This information should make it easier for debugging to find the right place in the program where the memory deallocation should occur

    📈 ROBOTFX MetaTrader Expert Advisors and Indicators to maximize profits and minimize the risks