Search code examples
c++visual-c++stdarray

array iterator not dereferencable error


There is a sample code that occurs the error as bellows. In release mode, it works and prints five '-'. However, in debug mode, it doesn't work and occurs a runtime error that is 'array iterator not dereferencable'.

environment details : Windows 7 64bit Visual Studio 2015 update 2

I don't know why there are deferences between release and debug mode. Thanks in advance.

#include <iostream>
#include <array>

static bool operator != (int * a, std::array<int, 5>::iterator &b)
{
    return a != &(*b);
}

int main(void)
{
    std::array<int, 5> arr = { 0,0,0,0,0 };

    for (auto* it = &arr[0]; it != arr.end(); it++)
    {
        std::cout << "-" << std::endl;
    }

    return 0;
}

Solution

  • You call *b when b is arr.end(). This causes undefined behaviour. You can only use * on an iterator that refers to an element of the array.