views:

424

answers:

4

Simple question: do I have to 'delete' or 'delete []' c? Does the language matter?

char c[] = "hello"
+11  A: 

In c++ that is not dynamic memory allocation. No delete[] will be needed.

Your example is basically a short-cut for this:

char c[6]={'h','e','l','l','o','\0'};
Gordon Wilson
Not exactly. I believe that performed inside a function, char c[] = "hello" copies a statically allocated string "hello" to the automatic (that is, on the stack) array, whereas char c[6]={'h','e','l','l','o','\0'} just creates the automatic array without any additional overhead
dmityugov
dmityugov, it's got the same outcome. how the compiler implements it is up to it. that's covered by the as-if rule: if the result is the same and no difference is noticable (by means of the so called observable behavior), the compiler can do it the way it wants. It's detailed at the begin of the std
Johannes Schaub - litb
from 2.13.4, String Literals: ..."An ordinary string literal has type “array of n const char” and static storage duration (3.7)" so I doubt the compiler has much to decide here
dmityugov
+1  A: 

No, the array is sized at compile time.

Abtin Forouzandeh
+11  A: 

The rule in C++ is that you use delete[] whenever you use new[], and delete whenever you use new. If you don't use new, as in your example, you do not need to delete anything.

In your example, the six bytes for the c array are allocated on the stack, instead of on the heap, if declared within a function. Since those bytes are on the stack, they vanish as soon as the function where they are declared returns.

If that declaration is outside any function, then those six bytes are allocated in the global data area and stay around for the whole lifetime of your program.

Greg Hewgill
The rule in C++ is that you should probably use boost::shared_ptr<T> every time you use new and boost::shared_array<T> every time you use new[], and never, ever, ever type delete.
Matt Cruikshank
match new's and deletes, a good point and a good rule of thumb.
Gordon Wilson
+2  A: 

you dynamically allocate memory when you put something on the heap. here, you are allocating the variable on the stack. If you were using the new operator or the malloc call, you'd be putting the variable on the heap.

you need to use delete (w/new) or free (w/malloc) to free the memory on the heap. the stack will be freed automatically when the function/method returns.

jdt141