Dynamic allocation |
Why And How
In many situations the programmer does not know when he writes a program
what objects he will need. It can be that he does not know if he will need a
given object, or or that he does not know the size of a required array.
The new operator allows to create an object at run-time. This operator takes
as an operand a type, which may be followed either by a number of elements
between [ ] or by an initial value between ( ) :
char *c = new char;
int *n = new int(123);
double *x = new double[250];
The area of memory allocated by new is still used out of the pointer’s
scope!
Bugs due to missing object deallocation are called memory leaks.
To free the memory, the programmer has to explicitly indicate to the computer
to do so. The delete operator (resp. delete[]) takes a pointer to a single
object (resp. an array of objects) as an operand and free the corresponding
area of the memory ;
delete n;
delete[] x;
The variables declared in the source code, without the usage of new and delete
are called static variables. Their existence is completely handled by the com-
piler who implicitly adds invisible news and deletes.
The operand pointer can be equal to 0 ; in that case delete (or delete[]) does
nothing. But deallocating an area which has already been deallocated has a
non-defined behavior (i.e. crashes most of the time).