If I have a function like:
void MyFunctoin(int size){
// ...
int *arr=new int[size];
// ...
}
delete?The answer to your title question is simple: yes, every new must be matched by a delete. In your case, since you used new[], there must be a delete[] somewhere.
But you don't need to write it yourself. It is usually much better to use a class that manages its own resources. In your case, you'd be better off using an STL container such as array<> or vector<>. This is, either:
std::array<int, size> arr; // fixed size (known at compile time)
or
std::vector<int> arr; // variable size
In vector, all the necessary calls to new and delete are done inside the container and you needn't care about them.
You could write your function this way:
#include <vector>
void MyFunctoin(int size){
// ...
std::vector<int> arr(size);
// ...
}
and there would not be any memory leak with no need to call delete anywhere. You don't need to specify size when constructing arr if you don't want to.
Yes, it is. Use smart pointers/STL containers (for example std::vector/boost::shared_array/std::unique_ptr<T[]> in your case).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With