-2

For a pointer to an int, I can do -

int *p = new int;
*p = 10;

delete p; // Step 1: Memory Freed
p = 0; // Step 2: Pointer set to NULL

Now, if I have a pointer to an int array -

int *p = new int[10];
p[1] = 1;
p[5] = 5;
delete[] p; // Step 1: Memory freed corresponding to whole array

Now, how to achieve 'Step 2' for this case?

theharshest
  • 7,767
  • 11
  • 41
  • 51
  • It's better to use nullptr when you are working with pointers. (It's not about downvotes, just a small guideline) – Ivan Gusev Jan 15 '14 at 09:10
  • Probably downvotes are here, because your title of the question contradicts your code. You don't have an array of pointers. You have a normal array of int. And a pointer, which points to the first element of this array. – Ivan Gusev Jan 15 '14 at 09:13
  • 1
    @IvanGusev And `NULL` if he doesn't have access to C++11 (but if he does, `nullptr` is far superior). – James Kanze Jan 15 '14 at 09:15
  • With new edits, I think the answer is obvious. p is just a pointer, so you could do the same as in first snippet. But please be aware, that sometimes setting a pointer to null may lead to hiding mistakes. E.g. if in your code you accidentally delete the same pointer twice - it's an indication that there are flaws in you code and you might forgot to delete some another pointer. In general second delete will cause a crash, so you will be aware of it. But if you set pointer as null, "delete 0" will just do nothing and you wouldn't know about the issue. – Ivan Gusev Jan 15 '14 at 09:23

1 Answers1

6

You don't have an array of int pointers. You just have an array of int. Since you only have one pointer, p, you can just do the same thing as you did previously:

p = 0; // or nullptr, preferably

If you did have an array of int pointers, you will probably have allocated them in a loop. In the same way, you can deallocate them and set them to 0 in a loop:

int* array[10];
for (auto& p : array) {
  p = new int;
}

// Some time later...

for (auto& p : array) {
  delete p;
  p = 0;
}

Do consider whether you need to set your pointers to null after deleteing them.

Community
  • 1
  • 1
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324