Page 250 - DCAP404 _Object Oriented Programming
P. 250
Unit 11: Pointers and Dynamic Memory Management
The first expression is used to allocate memory to contain one single element of type type. The Notes
second one is used to assign a block (an array) of elements of type type, where number_of_elements
is an integer value representing the amount of these. For example:
int * bobby;
bobby = new int [5];
In this case, the system dynamically assigns space for five elements of type int and returns a
pointer to the first element of the sequence, which is assigned to bobby.
Notes Note the now, bobby points to a valid block of memory with space for five elements
of type int.
The first element pointed by bobby can be accessed either with the expression bobby[0] or the
expression *bobby. Both are equivalent as has been explained in the section about pointers. The
second element can be accessed either with bobby[1] or *(bobby+1) and so on...
You could be wondering the difference between declaring a normal array and assigning dynamic
memory to a pointer, as we have just done. The most important difference is that the size of an
array has to be a constant value, which limits its size to what we decide at the moment of
designing the program, before its execution, whereas the dynamic memory allocation allows us
to assign memory during the execution of the program (runtime) using any variable or constant
value as its size.
The dynamic memory requested by our program is allocated by the system from the memory
heap. However, computer memory is a limited resource, and it can be exhausted. Therefore, it is
important to have some mechanism to check if our request to allocate memory was successful or
not.
C++ provides two standard methods to check if the allocation was successful:
One is by handling exceptions. Using this method an exception of type bad_alloc is thrown
when the allocation fails. Exceptions are a powerful C++ feature explained later in these tutorials.
But for now you should know that if this exception is thrown and it is not handled by a specific
handler, the program execution is terminated.
This exception method is the default method used by new, and is the one used in a declaration
like:
bobby = new int [5]; // if it fails an exception is thrown
The other method is known as nothrow, and what happens when it is used is that when a
memory allocation fails, instead of throwing a bad_alloc exception or terminating the program,
the pointer returned by new is a null pointer, and the program continues its execution.
This method can be specified by using a special object called nothrow, declared in header
<new>, as argument fornew:
bobby = new (nothrow) int [5];
LOVELY PROFESSIONAL UNIVERSITY 243