Which pointers do you have to delete to prevent leaks?

I had a program that had regular pointers and dynamic array pointers such as

int *numptr=#

and

1
2
3
int *arrayNum;

arrayNum=new int[5];


Now I obviously included the delete command delete [] arrayNum; for the second one (dynamic array) at the end of the program, but my teacher said I had forgotten to delete the other one (numptr). Do normal pointers have to be deleted at the end of the program as well??
You only delete what you new
You only delete[] what you new[]

If you did not use new or new[], then you should not use delete or delete[].

Your teacher may have meant for you to null the pointer out when you were done with it to avoid a dangling pointer, which is different from a memory leak.
Last edited on
So I equal the pointer to zero?
If you can use C++11, you would write pointer = nullptr;
If you can't use C++11 (e.g. the above doesn't work) then yes, you would usually write pointer = 0;

You should always null out pointers when you are done with them, even in both cases.
Last edited on
closed account (N8hM4iN6)
i think it's not right to delete numptr;, cause it's not used with a new, so numptr is not pointing at a dynamic variable or array.

And when i test such code in my compiler, it's not working.
There is a convoluted and rare reason to do such a thing:
1
2
3
4
5
int &num = *new int; //reference to heap-allocated int
int *numptr = # //these two lines are basically 'int *numptr = new int;'
delete numptr;
//or
delete #
It is a very rare and stupid case that you should never do or worry about - it is improper coding, but it is valid C++.
Topic archived. No new replies allowed.