K
K
ku4er992020-12-20 20:40:43
C++ / C#
ku4er99, 2020-12-20 20:40:43

What overflows the array?

Good day! The compiler throws an error

Run-Time Check Failure #2 - Stack around the variable 'arr' was corrupted.


Task: Sort matrix columns in descending order.

The code:
#include <iostream>
#include <time.h>

using namespace std;

#define N 9
#define M 6

void matrixsort(unsigned int *arr) {
  int temp;
  for (int i = 0; i < M - 1; i++) {
    for (int j = 0; j < N - i - 1; j++) {
      if (arr[j] < arr[j + 1]) {
        temp = arr[j + 1];
        arr[j + 1] = arr[j];
        arr[j] = temp;
      }
    }
  }
}

void showmatrix(unsigned int arr[N][M], string s) {
  string str = "Matrica " + s + " sortirovki:";
  cout << endl << str << endl << endl;

  for (int i = 0; i < N; i++) {
    for (int j = 0; j < M; j++) {
      cout << arr[i][j] << " ";
    }
    cout << endl;
  }
}

int main() {
  unsigned int arr0[N];
  unsigned int arr[N][M];
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < M; j++) {
      arr[i][j] = rand() % 50;
    }
  }
  showmatrix(arr, "do");
  int line = 0;
  while (line < N) {
    for (int j = line; j < line + 1; j++) {
      for (int i = 0; i < N; i++) {
        arr0[i] = arr[i][j];
      }
      arr0[M] = line;
      matrixsort(arr0);
      for (int i = 0; i < N; i++) {
        arr[i][j] = arr0[i];
      }
    }
    line++;
  }
  showmatrix(arr, "posle");
  return 0;
}

Actually, due to my ignorance, I can not find an error.
Here is the output:
5fdf8cc9ea3fd296559553.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-12-20
@ku4er99

void matrixsort(unsigned int *arr) {
  int temp;
  for (int i = 0; i < M - 1; i++) {

It should be written here for (int i = 0; i < N - 1; i++)because this is sorting, not matrix traversal.

while (line < N) {
    for (int j = line; j < line + 1; j++) {

It's some weird construct that causes j to go to N - 1, causing the error you're seeing. Instead, one could throw out the line altogether and simply write
for (int j = 0; j < M; j++) {
arr0[M] = line;

Here you spoil the matrix element by replacing it with the column number. Debugging like this?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question