Pergunta

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 ?

Foi útil?

Solução

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.

new int*[3] is an array that contain THREE pointers.

What you want is this (live at 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;

}

Outras dicas

With

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

you allocate an array of pointers of size 3. But than with

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

you access it with up to index 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 10instead of 3, e.g.

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).

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. 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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top