简体   繁体   English

c ++取消分配2d int数组错误

[英]c++ deallocate 2d int array error

I get very frustrating error in following piece of code. 在下面的代码段中,我得到非常令人沮丧的错误。 Thats my array. 多数民众赞成在我的数组。

int **tab2 = new int*[3];

I allocate this like it. 我像这样分配。

for(i = 0; i < 10; i++) {
    tab2[i] = new int[3];
    tab2[i][0] = 40;
    tab2[i][1] = 10;
    tab2[i][2] = 100;
}

Then after using it i want to destroy it. 然后,在使用它之后,我想销毁它。

for(i = 0; i < 10; i++) {
    delete [] tab2[i];
}
delete [] tab2;

And this causes core dump every single time. 这会导致核心转储每一次。 I tried many different ways to destroy it and every time get this error. 我尝试了许多不同的方法来销毁它,每次都收到此错误。 What im making wrong here ? 我在这里弄错了什么?

This 这个

int **tab2 = new int*[3];

does not do what you think it does. 不按照您的想法去做。

You want an array that will contain TEN (10) pointers, each to an array of THREE ints. 您需要一个包含十个(10)指针的数组,每个指针指向三个整数的数组。

new int*[3] is an array that contain THREE pointers. new int*[3]是一个包含三个指针的数组。

What you want is this (live at coliru) : 您想要的是这个(住在coliru)

#include <iostream>

int main() {

  int **tab2 = new int*[10];

  for(int i = 0; i < 10; i++) {
    tab2[i] = new int[3];
    tab2[i][0] = 40;
    tab2[i][1] = 10;
    tab2[i][2] = 100;
  }

  for(int i = 0; i < 10; i++) {
    delete [] tab2[i];
  }
  delete [] tab2;

}

With

int **tab2 = new int*[3];

you allocate an array of pointers of size 3. But than with 您分配了一个大小为3的指针数组。

for(i = 0; i < 10; i++) {
    tab2[i] = new int[3];
    //...
}

you access it with up to index 9 . 您最多可以访问索引9 That will surely go wrong. 那肯定会出错。 The deletion process looks fine to me. 删除过程对我来说很好。 To fix it, you should allocate an array of pointers with size 10 instead of 3 , eg 要修复它,您应该分配一个大小为10而不是3的指针数组,例如

int **tab2 = new int*[10];

Looks like what you're trying to do is to create an N by M array, where N is known at runtime and M is fixed (in this case, 3). 看起来您想要做的是创建一个N by M数组,其中N在运行时是已知的,M是固定的(在本例中为3)。

Why not just do this? 为什么不这样做呢?

{
    std::array<int, 3> defaults = {{ 40, 10, 100 }};
    std::vector<std::array<int, 3>> thing(10, defaults);
}

The vector, thing is automatically deallocated when it goes out of scope, and its size can be set at runtime. 向量超出范围时, thing会自动释放,它的大小可以在运行时设置。 You still access the structure in the same way: 您仍然可以通过相同的方式访问结构:

thing[1][2] = 3

Manual memory management can be easily avoided by using standard containers and smart pointers. 使用标准容器和智能指针可以轻松避免手动进行内存管理。 Doing so will keep you code cleaner, and have fewer opportunities for dangling pointers and memory leaks. 这样做将使您的代码更整洁,并减少了悬空指针和内存泄漏的机会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM