Question

I am a beginner in C++ and I have a doubt. If I have a code like this:

int* f(int n){               //global

int* arr = new int[n];
for(int i=0;i<n;i++)
arr[i]=i;

return arr;
}

void main() {

int n;
scanf("%d",&n);


int* arr1 = new int;  //or should I write just int* arr1; ?
arr1 = f(n);

delete [] arr1;  // or just delete arr1;
}

The question is should I delete arr1 as array or not since I declared it as pointer to int? The code doesn't make much sense but it is good as an example. I know there are a lot of similar question but I could not find the exact answer to my question.

Was it helpful?

Solution

If the allocation was made with new <type>[n] then the deallocation must be made with delete [].

All that counts when determining the correct form of delete is the form of new that was used in the allocation.

In your main function, you leak memory. You initialize arr1 with a call to new and then immediately overwrite that value with the new pointer returned by the call to f(). The call to new from main is simply wrong and should be removed. Write it simply like this:

int* arr1 = f(n);

And your main should be

int main()

OTHER TIPS

Write

int* arr1 = f(n);

and later

delete[] arr1;

the array object is allocated in f(), and delete deletes it. The pointer itself can not be deleted, just the object(array) it points to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top