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

时间:2017-04-02 17:37:57

标签: 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 xDim, yDim, zDim;
    TestStructure **testStructure;
    void init();

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

CPP:

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);
}

我很确定第二个就像第一个,但在两种情况下我都得到:

  

== 3854 == ERROR:AddressSanitizer:alloc-dealloc-mismatch(operator new vs free)on 0x62100008e900

我的错误在哪里?把它们扔在我脸上让我学习!

编辑:基本错误:使用delete(代表new)代替free(代表malloc)。

free替换上面的delete导致:

  

== 4076 ==错误:AddressSanitizer:线程T0中0x60600002c300上的new-delete-type-mismatch:

EDIT2:

请原谅我,delete[]代表数组部分:

  

== 4138 ==错误:AddressSanitizer:地址0x62100008e8f8上的堆缓冲区溢出,地址为pc 0x000000480b3d bp 0x7ffc5bcbc0f0 sp 0x7ffc5bcbc0e0

edit3 / SOLUTION :这是错误的方式。这似乎有效:

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

非常感谢@SomeProgrammerDude

0 个答案:

没有答案