分段错误但数组对象不会超出范围(C ++)

时间:2016-07-10 19:40:56

标签: c++ arrays oop multidimensional-array segmentation-fault

还有其他关于分段错误的常见原因的帖子,但我不认为我在这里创建的内置数组对象(result)在我分配值时不会超出范围它。
我认为这可能对未来有阵列不出界的人有所帮助,而且我还没有看到很多关于制作2D内置数组对象的东西 - 我见过的例子几乎完全是矢量或标准:数组对象。

这是可运行的相关代码:

matrix.h

#ifndef MATRIX_H
#define MATRIX_H

#include <initializer_list>
using std::initializer_list;

typedef unsigned int uint;

class Matrix {

  public:

    Matrix(uint rows, uint cols);  
    ~Matrix();  
    Matrix add(double s) const;  
    const uint numRows() const;  
    const uint numCols() const;  
    double & at(uint row, uint col);  
    const double & at(uint row, uint col) const;  

  private:

    uint rows, cols;
    double ** matrix;

    void makeArray() {
      matrix = new double * [rows];
      for(uint i = 0; i < rows; ++i) {
        matrix[i] = new double [cols];
      }
    }

};

#endif  

matrix.cpp

#include "matrix.h"
Matrix::Matrix(uint rows, uint cols) {
  //Make matrix of desired size
  this->rows = rows;
  this->cols = cols;

  makeArray();

  //Initialize all elements to 0
  for(uint i = 0; i < rows; ++i) {
    for(uint j = 0; j < cols; ++j) {
      this->matrix[i][j] = 0.0;
    }
  }
}
Matrix::~Matrix() {
  for(uint i = 0; i < numRows(); ++i) {
    delete[] matrix[i];
  }
  delete[] matrix;
}
const uint Matrix::numRows() const {
  return this->rows;
}

const uint Matrix::numCols() const {
  return this->cols;
}

double & Matrix::at(uint row, uint col) {
  return matrix[row][col];
}

const double & Matrix::at(uint row, uint col) const {
  return matrix[row][col];
}

Matrix Matrix::add(double s) const {
  uint r = this->numRows();
  uint c = this->numCols();

  Matrix * result;
  result = new Matrix(r, c);

  for(uint i = 0; i < r; ++i) {
    for(uint j = 0; j < c; ++j) {
      result->at(i,j) = (this->at(i,j)) + s;
    }
  }

  return * result;
}  

main.cpp

#include <iostream>
#include <cstdlib>
#include "matrix.h"

using namespace std;

typedef unsigned int uint;

int main() {

  Matrix * matrix;
  matrix = new Matrix(3, 2); //Works fine

  double scaler = 5;

  matrix->at(2,1) = 5.0; //Works fine

  Matrix r = matrix->add(scaler); //DOESN'T WORK

  return EXIT_SUCCESS;
}  

add函数导致分段错误错误的任何想法?我用来填充结果的for循环对象不会超出界限,而且我对C ++不太熟悉,不知道还有什么可能导致它。
提前谢谢。

1 个答案:

答案 0 :(得分:1)

问题是缺少手动定义的复制构造函数或赋值运算符,因为该类管理资源(内存)。

如果分配了类的实例,或者用于创建副本,则结果将是引用同一内存的两个不同对象。当这两个引用相同内存的对象被破坏时,内存被释放两次。结果是未定义的行为。

查找解决方案的“三规则”。在C ++ 11中,它通常变成“五条规则”或“零规则”(其中涉及首先使用技术来避免问题)。

add()函数中还存在一个非常重要的问题,因为它动态创建Matrix,然后返回它的副本。这会导致内存泄漏,即使解决了复制对象的问题。该函数实际上看起来像是用垃圾收集语言编写的东西 - 问题是C ++不是垃圾收集。