When you use the
new[1] keyword, a block of memory is allocated from the main memory, also known as the
heap. Unlike
new,
malloc( ), and
calloc( ) don't call the types constructor. The size of the block allocated, is determined how you used the
new keyword. For example:
1 2 3 4 5
|
// Allocate a single 4-byte integer, then initialize it to 10.
int *block_a( new int( 10 ) );
// Allocate 3 4-byte integers.
int *block_b( new int[ 3 ] );
|
Every block of memory allocated by
new must be released. This can be done by using the
delete[1] keyword. However, based on the type of block you allocated, your call to
delete may vary. For example:
1 2 3 4 5 6 7 8 9
|
// Allocate a single 4-byte integer, then initialize it to 10.
int *block_a( new int( 10 ) );
delete block_a;
// Allocate 3 4-byte integers.
int *block_b( new int[ 3 ] );
delete [ ] block_b;
|
If a pointer allocates multiple objects of the same type, or, in the form of an array( like
block_b in the examples ), you would call
delete [ ] < POINTER_IDENTIFIER >. If a pointer allocates only one object( like
block_a in the examples ), then you would call
delete < POINTER_IDENTIFIER >
If you plan on allocating memory with the same pointer after releasing previously allocated memory, make sure you set the pointer to
NULL prior to allocation.
Note that
new doesn't return
NULL on an allocation failure. Instead,
new throws a
bad_alloc exception
[2]. To force
new to return
NULL on allocation failure, you would explicitly tell it to, like this:
|
int *block( new ( std::nothrow ) int( 10 ) );
|
However, telling
new to not throw exceptions will mean if
new fails to allocate a block of memory, it's basically won't tell you. You will know if the allocation fails, however( the will program crash ).
References:
[1]http://www.cplusplus.com/reference/std/new/
[2]http://www.cplusplus.com/doc/tutorial/exceptions/
Wazzak