I use Dev-c ++. My code works as it should, but in the steppe the code does not work and gives an error:

Failed test # 2. Runtime error main: malloc.c: 2406: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size)> = MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0) 'failed. Aborted (core dumped)

What is the reason? Not going beyond the array?

#include <iostream> #include <vector> using namespace std; int main() { int n; cin >> n; vector <int> a(n); //ввод for (int i=0; i<n; i++) { cin >> a[i]; } //обработка int mem=a[n-1]; //сохранение последнего элемента вектора for (int i=n; i!=0; i--) { // массив сдвигается с конца swap(a[i],a[i-1]); // сдвиг вправо на 1 элемент } a[0]=mem; // замещение первого элемента последним до сдвига //вывод for (int i=0; i<n; i++) { cout << a[i] << " "; } } 

    2 answers 2

    You have here a line beyond the bounds of the array. Here before the cycle at 0 == n output in a[n-1] ; in the loop at the first step, when i == n exit to a[i] ; then with 0 == n output in a[0]

      First, such a shift cycle should begin with i = n - 1 , and not c i = n (implying that the size of the array is not zero). This is the cause of your error message. Yes, it is the output beyond the array.

      Secondly, once you are going to use swap(a[i], a[i - 1]) inside the loop, rather than assigning a[i] = a[i - 1] , then you absolutely do not need to remember the last element in mem , and then write it to the first. Your cycle in itself implements a cyclical shift to the right. All your mem manipulations are unnecessary extra work.

      In the "manual" implementation, it would be more appropriate to use the relocation construct / assignment, although in the specific case of the int type it is not essential

       T mem = std::move(a[n - 1]); for (auto i = n - 1; i > 0; --i) a[i] = std::move(a[i - 1]); a[0] = std::move(mem);