1

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

char c[] = "hello"

4 Answers 4

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'};
3
  • 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 8, 2009 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 Jan 9, 2009 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, 2009 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.

2
  • 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. Jan 8, 2009 at 4:15
  • match new's and deletes, a good point and a good rule of thumb. Jan 8, 2009 at 6:43
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.

1

No, the array is sized at compile time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.