I was reading an excellent answer to another question which gave these specific examples:
char[] array = {'a', 'b', 'c', '\0'};
Thing* t = new Thing[size];
t[someindex].dosomething();
I commented that, as good practice, you should add delete[]
to the second example, as this is the bit people forget leading to memory leaks.
But I can't remember if you need to delete[]
in the first instance. I don't think you do, because there's no new
so it's on the stack, but I'm not 100% sure that's right.
In C, if you are declaring your array as static ex: int a[10], no need to delete. It will be freed when your function ends or program terminates.
delete is used for one single pointer and delete[] is used for deleting an array through a pointer.
One of the most common data structures, especially for scientific and numerical programming, is a group of variables all of the same type. This is frequently called an array.
Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. Delete can be used by either using Delete operator or Delete [ ] operator. New operator is used for dynamic memory allocation which puts variables on heap memory.
I don't think you do, because there's no new so it's on the stack, but I'm not 100% sure that's right.
This reasoning is correct when the array
is defined inside a function, and is therefore on the stack. You must never use delete
on any objects that have been created on the stack without the use of new
. Using delete
on stack allocated objects will lead to undefined behavior.
If the definition char[] array = {'a', 'b', 'c', '\0'};
appeared at file scope, however, it will have static storage duration and will not be on the stack, but it still won't have been dynamically allocated and still must not be delete[]
d.
So, either way, don't delete[]
the array....
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