【问题标题】:Segmentation fault when passing values to dynamically allocated array将值传递给动态分配的数组时出现分段错误
【发布时间】:2018-01-17 17:16:50
【问题描述】:

我正在完成一项要求我模拟兰顿蚂蚁的任务。我在 Ant 类的构造函数中为二维数组动态分配了内存。指向该数组的指针是 Ant 类的成员。此外,我还为用于将这些值传递给数组的行和列定义了 get 函数。

Ant.hpp

#ifndef ANT_HPP
#define ANT_HPP

enum Direction {UP, RIGHT, DOWN, LEFT};

class Ant
{
private:
char** board;
char spaceColor;
Direction facing;
int rows, cols, steps, stepNumber;
int startRow, startCol, tempCol, tempRow;
int lastRow, lastCol;
int thisRow, thisCol;

public:
Ant();
Ant(int, int, int, int, int);
void print();
void makeMove();
};

Ant.cpp

Ant::Ant()
{
rows = 5;
cols = 5;
steps = 5;
startRow = 0;
startCol = 0;
stepNumber = 0;
facing = LEFT;
setThisRow(5);
setThisCol(5);
setLastRow(5);
setLastCol(5);
setSpaceColor(' ');
board = new char*[rows];
for(int i = 0; i < rows; ++i){
board[i] = new char[cols];
}
for(int i = 0; i < rows; ++i){
for(int i = 0; i < rows; ++i){
board[i][j] = ' ';
}
}
board[startRow][startCol] = '*';
}

char Ant::getSpaceColor()
{
return spaceColor;
}

void Ant::makeMove()
{
if(getSpaceColor() == ' '){
board[getLastRow()][getLastCol()] = '#';
}
}

int Ant::getLastRow()
{
return lastRow;
}

int Ant::getLastCol()
{
return lastCol;
}

main.cpp

#include "Ant.hpp"
#include <iostream>

using std::cout;
using std::endl;

int main()
{
Ant myAnt;
myAnt.print();
myAnt.makeMove();
return 0;
}

Gdb 报告了这行代码的分段错误:

board[getLastRow()][getLastCol()] = '#';

Gdb 能够打印 getLastRow() 和 getLastCol() 的准确值,但无法访问 board[getLastRow()][getLastCol()] 的内存。

我不知道我做错了什么,任何帮助将不胜感激

【问题讨论】:

  • 我们也不确定,因为您没有包含 getLastRow 等的代码
  • 变量board 未初始化为指向正确分配的内存块。
  • 我建议你远离 char** 并使用简单的 std::vector。按板寻址一个单元格[row_id*num_cols + col_id]

标签: c++ arrays pointers


【解决方案1】:

假设 board[getLastRow()][getLastCol()] 转换为 board[5][5],你就超出了缓冲区。你的棋盘是 0..4。

【讨论】:

    【解决方案2】:

    您正在通过越界访问数组元素来调用undefined behavior。您的setLastRow(5);setLastCol(5); 函数会导致您的 getLastRow()getLastCol() 函数都返回 5 的值,但由于数组是零索引,这意味着您正在访问 6th 元素。所以:

    board[getLastRow()][getLastCol()] = '#';
    

    你实际上是在打电话:

    board[5][5] = '#'; // undefined behavior because there are no 6 X 6 elements
    

    而您只能拥有4 的最大索引:

    board[4][4] = '#'; // OK as there are 5 X 5 elements
    

    一种解决方案是让您的函数分别返回lastRow - 1lastCol - 1

    【讨论】:

    • 我已经在 Ant 类的构造函数中初始化了板指针指向一个指针数组,但是问题仍然存在。
    • 是的,这似乎是导致问题的原因!非常感谢,过去一天我被这件事难住了
    【解决方案3】:

    分段错误通常是指程序正在访问一个未分配的地址。

    板[getLastRow()][getLastCol()]

    您可能需要检查数组的起始索引和结束索引。

    • 我认为您可以分配索引从 0 开始的二维数组
    • getLastRow()/Col 可能会返回行/Col 的大小
    • 因此,当索引从 0 开始时,您的最后一行索引将是 getLastRow()-1,同样的事情将适用于列

    产生 ==> board[getLastRow()-1][getLastCol()-1]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-28
      • 2014-12-10
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 2015-12-20
      相关资源
      最近更新 更多