0
void work() {
  int *p;
  p=new int[10];
  //some code....
}

I have a short question that in the work function, should i use delete[] operator? since when work function is over, p will be destroyed, which is wrong or right ? (My English is bad, i am sorry).

L.Nam
  • 173
  • 1
  • 7
  • 1
    There are a lot of disadvantages in using `new[]` and `delete[]`; with potential memory leaks being only one of them. You should avoid using them and prefer `std::vector` instead. – Ben Cottrell Apr 03 '16 at 08:47

4 Answers4

4

This will work as long as the code throws no exceptions...

void work() {
    int *p;
    p=new int[10];
    //some code....
    delete [] p;
}

This is better (but difficult to maintain):

void work1() {
    int *p;
    p=new int[10];
    try {
    //some code....
    } catch(...) {
        delete [] p;
    }
    delete [] p;
}

This is much better...

void work2()
{
    auto p = std::unique_ptr<int[]>(new int[10]);
    // some code...

    // memory is automatically deleted
}

And this is how you should do it...

void work3()
{
    auto v = std::vector<int>(10);
    // some code...
}
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
2

You're right, if you have no reference to p outside of the function, e.g. a global variable, then you need to call delete [] p right inside of the function, otherwise the reference to the allocated memory you want to free is lost.

Lorenz Leitner
  • 521
  • 7
  • 22
1

Yes, if integers are allocated using new int[10], you need to clean up using delete[], since it is an array.

Jens Munk
  • 4,627
  • 1
  • 25
  • 40
1

Yes, you need to release the memory from new.

Alternatively with C++11, you can use smart pointer:

void work() {
  std::unique_ptr<int[]> p{ new int[10] };
  //some code....
  // RAII will delete[] magically here
}

Alternatively, if you are using just few integers (10 in your case), that are known in compile time, you can do "normal" or static array. e.g.

void work() {
  /* static */ int p[10];
  //some code....
}

Alternatively, use std::vector:

void work() {
  std::vector<int> p{10};
  //some code....
  // RAII will delete[] magically here
}

Alternatively, with C++11 if array size is known in compile time, use std::array:

void work() {
  std::array<int,10> p;
  //some code....
  // RAII will delete[] magically here
}
Nick
  • 9,962
  • 4
  • 42
  • 80
  • 1
    If you want to use a fixed number of integers known at compile time, that is. – Lorenz Leitner Apr 03 '16 at 08:48
  • If this is your first code, use `std::vector`. if this is code for school, use `delete[]`, because in schools they teach you `C with classes` and for good or bad, they want to see you can manage the memory yourself, as it would be done in `C`. – Nick Apr 03 '16 at 09:03