Department of Engineering

IT Services

Memory Allocation

Space is automatically set aside for variables when they are defined, but sometimes you don't know beforehand how many variables you'll need or just how long an array might need to be. The Standard Library copes with such situations but you may need to deal with things yourself.

The new command creates space ``on the fly''. new[] creates arrays. There are corresponding delete and delete[] calls.

int i;
cout <<"Type an integer ";
cin >> i;
int *ia = new int[i];

creates an integer array of the required size that can be destroyed by

delete[] ia;

If there's not enough memory for new to provide what you want, it will cause a bad_alloc exception (see section 10 for details).