C++ 3d数组作为双指针,使用后释放内存

C++ 3d数组作为双指针,使用后释放内存,c++,pointers,multidimensional-array,memory-management,free,C++,Pointers,Multidimensional Array,Memory Management,Free,首先,让我说,一切都像一个魅力,但记忆的释放。也许这纯粹是巧合,我没有任何问题,我的基本理解是错误的 另外,请不要告诉我“改用std::vector之类的东西”,因为我想先学习和理解基础知识 现在来看看代码: class Test { public: Test(const unsigned int xDim, const unsigned int yDim, const unsigned int zDim); ~Test(); private: unsigned int

首先,让我说,一切都像一个魅力,但记忆的释放。也许这纯粹是巧合,我没有任何问题,我的基本理解是错误的

另外,请不要告诉我“改用
std::vector
之类的东西”,因为我想先学习和理解基础知识

现在来看看代码:

class Test
{
public:
    Test(const unsigned int xDim, const unsigned int yDim, const unsigned int zDim);
    ~Test();

private:
    unsigned int xDim, yDim, zDim;
    TestStructure **testStructure;
    void init();

    int to1D(int x, int y, int z) { return x + (y * xDim) + (z * xDim * yDim); }
}
cpp:


非常感谢@SomeProgrammerDude

您用
new
分配的资源,您必须用
delete
释放资源。和
new[]
匹配
delete[]
。和
malloc
with
free
@Someprogrammerdude谢谢,如果我更改为delete,我会得到>==4076==ERROR:AddressSanitizer:new delete type在线程T0的0x60600002c300上不匹配:数组中的元素,使用
new
分配的元素必须使用
delete
删除。数组本身,你用
new[]
分配,你必须用
delete[]
@Someprogrammerdude将其添加为答案,这样我就可以接受了?请注意,你实际上不需要在
init()
中使用
toad(x,y,z)
。您可以使用额外的索引,例如
k
,类似于
testStructure[k++]=…
。也不需要所有的<>代码> -> ,并考虑使用构造函数。
Test::Test(const unsigned int xDim, const unsigned int yDim, const unsigned int zDim)
{
    this->xDim = xDim;
    this->yDim = yDim;
    this->zDim = zDim;
    this->testStructure = new TestStructure *[xDim * yDim * zDim];

    init();
}

void Test::init()
{
    for(int x = 0; x < xDim; x++)
        for(int y = 0; y < yDim; y++)
            for(int z = 0; z < zDim; z++)
            {
                this->testStructure[to1D(x, y, z)] = new TestStructure(
                        x - xDim / 2,
                        y - yDim / 2,
                        z - zDim / 2);

...
}
Test::~Test()
{
    for(int x = 0; x < xDim; x++)
        for(int y = 0; y < yDim; y++)
            for(int z = 0; z < zDim; z++) {
                free(this->testStructure[to1D(x, y, z)]);
            }
    free(this->testStructure);
}
Test::~Test()
{
    for(int a = 0; a < xDim * yDim * zDim; a++) {
        free(this->testStructure[a]);
    }

    free(this->testStructure);
}
Test::~Test()
{
    for(int a = 0; a < xDim * yDim * zDim; a++) {
        delete(this->testStructure[a]);
    }
    delete[] this->testStructure;
}