简体   繁体   中英

Segmentation fault C++ Program

I want to write a program to construct an*n matrix and fill it with 1 to n^2. but I get a segmentation fault( core dumped).

I have no clue why this happens. Any help will be appreciated.

  int array[n][n];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      array[i][j] = t;
      t++;
    }
 

I want to write a program to construct an*n matrix and fill it with 1 to n^2

You can either use a nested standard container or write your own user-defined class modelling a matrix data structure. Also note that there are plenty of linear algebra libraries providing well designed and tested matrix classes.

If you decide to implement one, this may a basic starting point

class Matrix
{
    size_t rows_, cols_;
    std::vector<int> m_;   // Note that this is ONE vector
public:
    Matrix() = default;
    Matrix(size_t r, size_t c) 
        : rows_{r}, cols_{c}, m_(r * c)
    {}
    size_t n_rows() const noexcept { 
        return rows_;
    }
    size_t n_columns() const noexcept {
        return cols_;
    }

    // I prefer to overload operator() for matrices, instead of operator[]. We need a little
    // formula to calculate the 1D index, given the 2D indices.
    auto operator() (size_t r, size_t c) const {
        return m_[r * cols_ + c];
    }
    auto& operator() (size_t r, size_t c) {
        return m_[r * cols_ + c];
    }

    auto begin() {
        return m_.begin();
    }
    auto end() {
        return m_.end();
    }
    // You may want the const version and cbegin(), cend(), too.
    // ...
};

Having that, you can complete your task in a couple of ways

// Using a nested loop
Matrix a(n, n);
for (size_t i{}, k{}; i < a.n_rows(); ++i) {
    for (size_t j{}; j < a.n_columns(); ++j) {
        a(i, j) = ++k;
    }        
}
// Using std::iota from <numeric> header
Matrix b(n, n);
std::iota(b.begin(), b.end(), 1);

I get a segmentation fault (core dumped). I have no clue why this happens.

Those lines

int n;
cin >> n;
int array[n][n];

Declare a Variable Length Array, which is not a standard compliant container. Some compilers provide theese as an extension. In particular, gcc also has the following documentation (emphasis mine).

6.20 Arrays of Variable Length

Variable-length automatic arrays are allowed in ISO C99 , and as an extension GCC accepts them in C90 mode and in C++ . These arrays are declared like any other automatic arrays, but with a length that is not a constant expression . The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.

Note the use of the automatic term.

In the comments, you say that you are testing the program with a size of 2000, which is probably too big for your environment. See eg why is stack memory size so limited? .

Some problems to be solved in your code:

  1. The variable length array (VLAs) are not a part of C++ standard. Thus, using syntax like:

     int n = 10; // non-const value int incorrect_array[n][n]; // invalid

    The array size must be known to compile time.

  2. Since the size of the array provided by you in the question is yet unclear, stack overflow may be another reason of the segfault in case you are overflowing the array size a gigantic number.


Revised edition of the same code:

#include <iostream>
#include <vector>

// Using this syntax just to avoid 'std::' prefix everywhere
// in this program.
using namespace std;

int main(void) {
  // Initializing multidimensional vector which will work as an array
  vector<vector<int>> multiDim;
  int size;
  int a = 1;

  cout << "The NxN size: ";
  cin >> size;

  // Providing a size of the multi-dim array
  multiDim.resize(size, vector<int>(size));

  // Initializing 1 to n^2
  for (int i{}; i < size; i++)
    for (int j{}; j < size; j++)
      multiDim[i][j] = a++;
  
  // Uncomment the next lines 5 lines to see output preview
  // for (const auto& it : multiDim) {
  //   for (const auto& subIt : it)
  //     cout << subIt << '\t';
  //   cout << endl;
  // }

  return 0;
}

The output would be:

The NxN size: 5
1       2       3       4       5
6       7       8       9       10
11      12      13      14      15
16      17      18      19      20
21      22      23      24      25

You can ask further in the comments if you have any confusion yet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM