Hi,
I'm new to C++, and im confused about arrays and pointer. Could someone tell me how can i properly delete a pointer. Like for example,
int *foo;
foo = new int[10];
delete foo;
or
delete [] foo;
Thanks.
Hi,
I'm new to C++, and im confused about arrays and pointer. Could someone tell me how can i properly delete a pointer. Like for example,
int *foo;
foo = new int[10];
delete foo;
or
delete [] foo;
Thanks.
If you do new <type>[]
you must do delete []
. It's a simple enough rule, and worth remembering.
If you allocate an array of objects using the new []
operator then you must use the delete []
operator and therefore the non-array new
can only be used with the non-array delete
.
int *a = new int[10];
int *b = new int;
delete [] a;
delete b;
It's:
delete[] foo;
Edit: Modern compilers really need you to use the correct delete
operator, or they may leak memory or fail to run the proper destructors.
(I earlier stated that it didn't make a difference in practice. About 10 years ago, I tried many different compilers and failed to find one that actually leaked memory if you mistakenly omitted the []
. However the howls of the mob - see below - have forced me to re-try my experimentation, and it seems that modern compilers/libc++s really do care.)
You walked in the front door and left it open. Then you walked through to the back door and tried to close it but you smashed it because it was already closed.
foo = new int [10]; // so when you open the front door
delete [] foo; // please remember to close the front door.
foo = new int; // and when you open the back door
delete foo; // please remember to close the back door.
Don't mix them up!
Anytime you new
ed an array you use delete[]
. Sometimes you new'ed an array using new
- then you still have to use delete[]
- no way out. So it's not exactly a rule "use delete[] when you new[]'ed" but rather "use delete[] when deleting an array".
typedef int array[5];
int *a = new array;
delete[] a; // still delete[] !