Dr. Debasish Jana Dr. Debasish Jana -4 years ago 128
C++ Question

Is c++ delete [] applicable to primitive types

In C++, if I have a dynamically allocated array of primitive type, is it necessary to use delete [] to prevent memory leakage?
For example,

char * x = new char[100];
delete x; // is it required to call delete [] x?
struct A {
A *p = new A[30];
delete [] p; // delete p would cause memory leakage

Please comment.

Answer Source

Dynamic memory in C++.

pointer = new T
pointer = new T [number_of_elements]

The first expression is used to allocate memory to contain one single element of type T. The second one is used to allocate a block (an array) of elements of type T, where number_of_elements is an integer value representing the amount of these. For example:

1.  int * foo;
2.  foo = new int [5]; 

In the below statements, first statement releases the memory of a single element allocated using new, and the second one releases the memory allocated for arrays of elements using new and a size in brackets ([]).

1. delete pointer;
2. delete[] pointer;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download