【问题标题】:Deallocating memory of this particular 2d array释放这个特定二维数组的内存
【发布时间】:2017-07-14 17:49:22
【问题描述】:

我目前正在使用特定的 API,因此我必须使用原始指针,但是鉴于指针的特定排列,我不确定如何最好地清除内存并避免这样做的任何未定义行为。

double *data1 = new double[rows*columns];
double **data2 = new double*[rows];
data2[0] = data1;  // Point to first row

for (int i = 1; i < columns; i++) {
    data2[i] = data2[i - 1] + rows;
}

我尝试过类似下面的方法,但我认为它不正确。

for(int i = 0; i < rows; i++) {
    delete [] data2[i];
}
delete [] data2;
delete [] data1;

【问题讨论】:

  • 您是否考虑过改用std::vector
  • 如果你有 2 个news,你应该有 2 个deletes。您的示例有 rows + 2 删除。基本上,计算你拥有的新闻和删除的数量,它们最终应该是相等的。
  • 这里删除的顺序有影响吗?
  • 不,没有任何区别。

标签: c++ pointers memory-management


【解决方案1】:

谁拥有什么?

这个问题将决定你如何删除对象。

我认为您正在做的是创建一个大数组来保存二维数据数组,然后创建另一个数组来保存指向每行开头的指针。

所以这是两个新闻,因此是两个删除。

这样可视化可能更容易:

struct matrix_view
{
    int rows, columns;

    // this pointer owns a block of doubles
    double* entire_buffer = nullptr;

    // this pointer owns a block of pointers, but not the memory
    // they point to
    double** row_pointers = nullptr;
};

matrix_view create_matrix(int rows, int columns)
{
    auto result = matrix_view{ rows, columns, nullptr, nullptr };

    auto size = rows * columns;
    result.entire_buffer = new double [size];
    result.row_pointers = new double* [rows];
    auto first = result.entire_buffer;
    auto last = first + size;
    auto dest = result.row_pointers;
    while (first != last) {
        *dest++ = first;
        first += columns;
    }
    return result;
}

void destroy_matrix(matrix_view m)
{
    // always destroy in reverse order

    delete [] m.row_pointers;
    delete [] m.entire_buffer;
}

【讨论】:

    猜你喜欢
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 2022-01-06
    • 2011-11-05
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多