Undefined behaviour with CopyBuffer and ArraySetAsSeries

 

CopyBuffer is presenting a problem when copying to an array that has been marked with ArraySetAsSeries to have reverse order of indexing when you are shrinking the array in the process.

Aparently, the data is copied to the wrong address and then discarded by the resizing.

The only way to achieve the expected outcome, it to either have the array resized with ArrayResize first, or call CopyBuffer twice. This behaviour is not documented and clearly is a bug.

Here is an example that shows the problem, the two consecutive CopyBuffer calls generate different outputs:

int h_rsi;
double buffer[];

int OnInit()
{
    h_rsi = iRSI(_Symbol, _Period, 22, PRICE_MEDIAN);
    ArraySetAsSeries(buffer, true);
    return INIT_SUCCEEDED;
}

void OnTick()
{
    if ((rand() & 1) > 0)
    {
        double a, b;
        CopyBuffer(h_rsi, 0, 0, 1, buffer);
        a = buffer[0];
        CopyBuffer(h_rsi, 0, 0, 1, buffer);
        b = buffer[0];
        if (a != b)
        {
            Print("Values are different! a = ", a, " b = ", b);
        }
    }
    else
    {
        CopyBuffer(h_rsi, 0, 10, 100, buffer);
    }
}