尝试写入矩阵后的C ++分段故障 [英] C++ Segmentation Fault After When Trying to Write to Matrix

查看:157
本文介绍了尝试写入矩阵后的C ++分段故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个3D矩阵,我分配为一块内存,但当我尝试写入darn的东西,它给我一个分段的错误。这件事对两个维度工作正常,但由于某种原因,我有麻烦的第三个...我不知道在分配的错误在哪里。

I have this 3D matrix I allocated as one block of memory, but when I try to write to the darn thing, it gives me a segmentation fault. The thing works fine for two dimensions, but for some reason, I'm having trouble with the third...I have no idea where the error is in the allocation. It looks perfect to me.

以下是代码:

phi = new double**[xlength];
phi[0] = new double*[xlength*ylength];
phi[0][0] = new double[xlength*ylength*tlength];
for (int i=0;i<xlength;i++)
{
    phi[i] = phi[0] + ylength*i;
    for (int j=0;j<ylength;j++)
    {
        phi[i][j] = phi[i][0] + tlength*j;
    }
}

任何帮助将非常感谢。 (是的,我想要一个3D矩阵)

Any help would be greatly appreciated. (Yes, I want a 3D matrix)

此外,这是我得到的分段错误,如果它是重要的:

Also, this is where I get the segmentation fault if it matters:

for (int i = 0; i < xlength; i++)
    {
        for (int j = 0; j < ylength; j++)
        {
            phi[i][j][1] = 0.1*(4.0*i*h-i*i*h*h)
            *(2.0*j*h-j*j*h*h);
        }
    }

phi = new double*[xlength];
phi[0] = new double[xlength*ylength];
for (int i=0;i<xlength;i++)
{
    phi[i] = phi[0] + ylength*i;
}


推荐答案

您没有分配其他子矩阵例如 phi [1] phi [0] [1]

You did not allocate other submatrixes like e.g. phi[1] or phi[0][1]

您至少需要

phi = new double**[xlength];
for (int i=0; i<xlength; i++) { 
    phi[i] = new double* [ylength];
    for (int j=0; j<ylength; j++) { 
       phi[i][j] = new double [zlength];
       for (k=0; k<zlength; k++) phi[i][j][k] = 0.0;
    }
}

您应该考虑使用 std :: vector (甚至,如果在C ++ 2011中, std :: array ),即

and you should consider using std::vector (or even, if in C++2011, std::array), i.e.

std::vector<std::vector<double> > phi;

然后使用 std :: vector 需要 phi.resize(xlength)和一个循环来调整每个子元素的大小 phi [i] .resize(ylength)等。

and then with std::vector you'll need to phi.resize(xlength) and a loop to resize each subelement phi[i].resize(ylength) etc.

如果您想一次分配所有内存,您可以

If you want to allocate all the memory at once, you could have

double* phi = new double[xlength*ylength*zlength]

但是您不能使用 phi [i] [j] [k] 符号,因此您应该

but then you cannot use the phi[i][j][k] notation, so you should

#define inphi(I,J,K) phi[(I)*xlength*ylength+(J)*xlength+(K)]

并写入 inphi(i,j,k) phi [i] [j] [k]

第二个代码不工作:它是未定义的行为(它不会崩溃,因为你是幸运的,它可能在其他系统崩溃....),只是一些内存泄漏,不会崩溃(但可能崩溃后,甚至可能通过重新运行程序)。使用内存泄漏检测器,如 valgrind

Your second code does not work: it is undefined behavior (it don't crash because you are lucky, it could crash on other systems....), just some memory leak which don't crash yet (but could crash later, perhaps even by re-running the program again). Use a memory leakage detector like valgrind

这篇关于尝试写入矩阵后的C ++分段故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆