程序编译但偶尔崩溃引用原因 255 (CodeBlocks)

Program Compiles but occasionally crashes citing reason 255 (CodeBlocks)

您好 :) 我是一个非常新的程序员,无法弄清楚为什么会出现此错误。解释一下,当我 运行 行中具有不同值的程序(下面的代码)

array2D *a = new array2D(320,240);

(例如,将 320 和 240 更改为 32 和 24)程序在执行 getSize 函数或执行 prtValue 函数(更常见的是前者)后的某个时间崩溃。然而,当我构建代码时,无论我在上一行中有什么值,它 returns 0 个错误和 0 个警告。

我已经在 cpp.sh 上测试了代码,该站点每次都准确地更改值并输出 correct/complete 结果,所以我想知道这是否是 CodeBlocks/my 硬件问题?调试器也只有returns一个问题,而且好像是setValue函数的问题,但我的外行看不出问题所在。

为无知道歉。同样,我在这方面几乎没有经验,有点不知所措。预先感谢您可能提供的任何帮助。

#include <iostream>
using namespace std;

class array2D
{
protected:
    int xRes;
    int yRes;
    float ** xtable;
public:
    array2D (int xResolution, int yResolution); 
    void getSize(int &xResolution, int &yResolution);
    void setValue(int x,int y,float val);
    float getValue(int x,int y);
    ~array2D();
};

array2D::array2D(int xResolution, int yResolution)
{
    xRes=xResolution;
    yRes=yResolution;

    xtable = new float*[xResolution];

    for(int i=0;i < xResolution;i++)
    {
        xtable[i] = new float[yResolution];
    }

    for(int i=0;i < xRes;i++)
    {
        for(int j=0;j < yRes;j++)
        {
            xtable[i][j]=0;
        }
    }
}

void array2D::getSize(int &xResolution, int &yResolution)
{
    xResolution=xRes;
    yResolution=yRes;
    cout << "Size of Array (rows, columns): " << xResolution << ", " << yResolution << endl;
}

void array2D::setValue(int x,int y,float val)
{
    xtable[x][y] = val;
}

float array2D::getValue(int x,int y)
{
    return xtable[x][y];
}

array2D::~array2D(){
    cout << "Destructing array" << endl;
}

int main()
{
    array2D *a = new array2D(32,24);
    int xRes, yRes;
    a->getSize(xRes,yRes);
    for(int i=0;i < yRes;i++)
    {
        for(int j=0;j < xRes;j++)
        {
            a->setValue(i,j,100.0);
        }
    }

    for(int j=0;j < xRes;j++)
    {
        for(int i=0;i < yRes;i++)
        {
            cout << a->getValue(i,j) << " ";
        }
        cout << endl;
    }

    a->~array2D();
}

您在以下块中错误地使用了 xResyRes

for(int i=0;i < yRes;i++)
{
    for(int j=0;j < xRes;j++)
    {
        a->setValue(i,j,100.0);
    }
}

因此,当 xResyRes 不同时,您最终会访问不应该访问的内存。这会导致未定义的行为。

交换他们。使用:

for(int i=0;i < xRes;i++)
{
    for(int j=0;j < yRes;j++)
    {
        a->setValue(i,j,100.0);
    }
}