0

Possible Duplicate:
delete[] an array of objects

The memory is allocated as follows:

struct foo {
  int size;
  int * arr;
};

(*structA).arr = new int[(*structA).size];

How does one deallocate it?

Community
  • 1
  • 1
  • 1
    You just call "delete (*structA).arr;" and you are golden? No need to specify how much memory needs to be freed. – SinisterMJ Nov 17 '12 at 00:16
  • 1
    General rule: exactly one `delete` for each `new`, exactly one `delete[]` for each `new[]`. – Robᵩ Nov 17 '12 at 00:54

2 Answers2

4

Anything you allocate with new[] must be deleted with delete[]:

structA->arr = new int[structA->size];
...
delete[] structA->arr;

In this particular example, it would be better to use std::vector instead. Let it handle the memory allocation and deallocation for you. You can use its size() method to determine how many items it is holding:

struct foo {
  std::vector<int> arr;
};

structA->arr.resize(some value here);
...
int size = structA->arr.size();
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • This looks nice, thanks - but originally, I programmed the whole thing using vectors and it was too slow to pass some authomated benchmarks so I rewrote it using arrays. –  Nov 17 '12 at 00:33
  • @Grant : I guarantee `vector<>` was not the source of your bottlenecks. – ildjarn Nov 17 '12 at 01:41
  • Vectors are just as fast as new[arraySize], so they will not be the slowdown. (well, minisculely slower, but completely and utterly neglible) – SinisterMJ Nov 17 '12 at 07:54
  • `vector` allocation of POD types is just as fast as a raw array. I'm guessing that the `vector` was probably being passed around by value, so a lot of time was wasted making copy-constructed temps. – Remy Lebeau Nov 17 '12 at 17:10
3

The memory allocated will be deleted when you call

delete[] (*structA).arr;

As for your struct, it depends on whether you allocated your struct on the heap or the stack.

SinisterMJ
  • 3,425
  • 2
  • 33
  • 53
  • Just one additional question: how would I do that with 2-dimensional array of structures? Defined like this: int (*foo)[2] = new int[size][2]; –  Nov 17 '12 at 00:36
  • 1
    Exactly the same. "delete[] foo;" and you are good. You can test this with a debugger, and check the application's current memory usage. – SinisterMJ Nov 17 '12 at 07:57