1

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

char c[] = "hello"
Sam
  • 7,252
  • 16
  • 46
  • 65

4 Answers4

12

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'};
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
Gordon Wilson
  • 26,244
  • 11
  • 57
  • 60
  • 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 Jan 08 '09 at 15:17
  • 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 Jan 09 '09 at 12:13
  • 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 Jan 11 '09 at 10:23
12

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
  • 951,095
  • 183
  • 1,149
  • 1,285
2

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
  • 4,993
  • 6
  • 35
  • 36
1

No, the array is sized at compile time.

Abtin Forouzandeh
  • 5,635
  • 4
  • 25
  • 28