【问题标题】:segmentation error after printing matrix, but is fixed after printing extra line (ostream << opertator)打印矩阵后的分割错误,但在打印额外的行后修复(ostream << 运算符)
【发布时间】:2018-10-16 02:51:10
【问题描述】:

仅创建一个矩阵并将其打印出来后,我得到一个分段错误...我的矩阵的所有字符都被打印但在我打印的最后一行之后:

std::cout << endl;

我得到了分段错误。

我的代码:

标题:

class Board{

    private:
        struct coord {
            int x;
            int y;
        };
        coord _coord;

        char** board;
        int size;

    public:

        Board(int v);   
        //~Board();
        friend std::ostream& operator<<(std::ostream& os, Board const &b); 
};

我的 CPP 代码:

Board::Board(int v)
{
    size = v;
    board = new char* [size];

    for (int i=0; i<size; i++)
    {
        board[i] = new char[size];
        for(int j = 0 ; j < size ; j++){
            board[i][j] = '*';
        }
    }
}

ostream& operator<<(std::ostream& os, Board const &b)

    {
        for(int i = 0 ; i < b.size ; i++){
            for(int j = 0 ; j < b.size ; j++){
                cout << b.board[i][j] << " ";
            }
            cout << endl; // when (i == 3) the debug tells me after this I am thrown out
        }
        //cout << " "  << endl;

    }

我的主要:

#include "Board.h"
#include <iostream>
#include <vector>
//#include <map>
using namespace std;

int main() {
    Board board1{4};  // Initializes a 4x4 board
    cout << board1 << endl; 
    return 0;
}

然后我得到:

* * * * 
* * * * 
* * * * 
* * * * 
Segmentation fault

但是如果我注释掉:"//cout 我没有任何分段错误。

问题出在哪里?它看起来太简单了,但仍然出现错误。 (有了额外的 cout

我看到here 在某些情况下,我正在访问我不应该到达的内存区域,但我知道并且我正在询问我的特定代码,这就是它的原因不是重复的。另外,here 有一个类似的问题,但很具体,与我的问题无关。

【问题讨论】:

  • 如果您使用 C++ 编程,我建议您使用 STL 容器。你的代码会更干净,更不容易出错
  • @Jodocus 感谢您的意见,我尝试编辑更多问题,希望它符合标准
  • 提供一些代码,让我们重现您的问题。在那之后,鉴于您在类构造函数中操作指针数组,我会说您的问题是运算符函数尝试访问取消引用的内存(因此出现段错误)。我强烈建议使用 std::vector 创建实现矩阵类

标签: c++ segmentation-fault ostream


【解决方案1】:

这甚至可以编译吗?您缺少 operator

    friend ostream& operator<<(std::ostream& os, Board const &b)
    {
        for (int i = 0; i < b.size; i++) {
            for (int j = 0; j < b.size; j++) {
                os << b.board[i][j] << " ";
            }
            os << endl; // when (i == 3) the debug tells me after this I am thrown out
        }

        os << " "  << endl;
        return os;
    }

cout 是可用的 ostream 对象之一(还有 cerr 和 clog),您希望您的操作员支持所有这些对象。话虽如此,您应该使用 STL 容器而不是使用原始指针。

【讨论】:

  • 谢谢!是的,它可以编译,因为最后允许执行 cout
  • "这还能编译吗?"它可能会编译,如果幸运的话,编译器会发出警告。几个月前这让我很伤心。该程序甚至可以与-O0 一起使用,并且仅在我引入一些优化时才崩溃。
  • VC++ 确实会发出 level1 的警告,并且会自动升级为错误。关闭所有警告 (/W0) 也不能消除错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-15
相关资源
最近更新 更多