Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you need to delete C-style arrays?

Tags:

c++

arrays

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.

like image 611
deworde Avatar asked Jul 08 '19 08:07

deworde


People also ask

Do I need to delete arrays in C?

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.

When to use delete [] or delete?

delete is used for one single pointer and delete[] is used for deleting an array through a pointer.

What is a C style array?

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.

What does delete [] array do in C++?

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.


1 Answers

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....

like image 92
ruohola Avatar answered Oct 09 '22 07:10

ruohola