CArrayObj Update corrupting record

 

Hello,

Could someone tell me how to fix this code please? It's exiting with an invalid pointer after the Update operation.

#include <Arrays/ArrayObj.mqh>

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
class test_t : public CObject
  {
public:
   double            a;
   double            b;
   datetime          c;

                     test_t(void)
      :              a(0.0), b(0.0), c(0) {};
                     test_t(const test_t& src)
      :              a(src.a), b(src.b), c(src.c) {};
  };

CArrayObj *obj = new CArrayObj;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   obj.Add(build_struct(1.0,2.0,iTime(NULL,0,0)));

   test_t *r = obj.At(0);

   r.a = 3.0;

   PrintFormat("Before obj[0].a = %f", r.a);
   
   obj.Update(0,r);
   
   PrintFormat("After obj[0].a = %f (invalid pointer)", r.a);

   delete obj;
  }
//+------------------------------------------------------------------+
test_t* build_struct(const double a, const double b, const datetime c)
  {
   test_t *t=new test_t();
   t.a = a;
   t.b = b;
   t.c = c;

   return t;
  }

What am I doing wrong please?

Documentation on MQL5: MQL5 programs / Runtime Errors
Documentation on MQL5: MQL5 programs / Runtime Errors
  • www.mql5.com
The executing subsystem of the client terminal has an opportunity to save the error code in case it occurs during a MQL5 program run. There is a predefined variable _LastError for each executable MQL5 program. Before starting the OnInit function, the _LastError variable is reset...
 

You are trying to update element 0 in your collection, a pointer to a test_t instance, with itself.

Unfortunately the CArrayObj implementation doesn't check this and so it deletes exactly the same pointer you are turning in. Result of this operation is that you lost your test_t instance and any access to it will be invalid.

Learn about classes, instances and pointers thereof before going on.

   PrintFormat("Before obj[0].a = %f", r.a);

   r.a = 3.0;
   
   //obj.Update(0,r);
   
   PrintFormat("After obj[0].a = %f", r.a);
 
lippmaje:

You are trying to update element 0 in your collection, a pointer to a test_t instance, with itself.

Unfortunately the CArrayObj implementation doesn't check this and so it deletes exactly the same pointer you are turning in. Result of this operation is that you lost your test_t instance and any access to it will be invalid.

Learn about classes, instances and pointers thereof before going on.

Thanks