Sometimes you are not aware in advance how much memory you will need store some information, like a string entered by a user. You can declare a variable that is large enough to store any expected data but its a waste of memory, the alternative way to do this is to allocate the memory at runtime and use the Dynamic memory allocation concept.
Unlike the memory the created at compile time, The memory declared at runtime allocated in the heap which is unused memory that allows the applications to allocate memory at runtime
As you know, the computer resources are limited and dynamic memory allocation may fail if there is no enough free memory in the heap to allocate the memory you want.
C++ provides you with 2 ways to check if the allocation succeeded or not.
The first one is by handling exceptions. When memory allocation fails, bad_alloc exception is thrown and handling this exception with the proper handler will prevent your application from termination.
The second one is to use nothrow object while creating the pointer. Using this way, there is no exceptions will be thrown and you the pointer will be returned with the value of nullptr and by checking the value of the pointer you know if the allocation process succeeded or not.
Example :
int *x = (nothrow) new x[5];
if (x==nullptr)
{
//do something
}
No comments:
Post a Comment