1. Functions of malloc/calloc/realloc/valloc/alloca/memalign in C:
Such a memory allocation function returns a null pointer when the memory allocation fails.,Therefore,When a call returns,The method for checking the return value is relatively simple.,You only need to compare it with a null pointer.;
For example:
Char * P = (char *) malloc (1204);
If (P = NULL)
{
// Error handle;
};
Char * PP = (char *) calloc (3,1024);
If (Pp = NULL)
{
// Error handle;
};
Ii. New operator in C ++:
When the new operator in C ++ fails to allocate memory, the default operation throws a built-in exception. , Instead of directly returning a null pointer ; In this case , Then compare the returned value with a null pointer. , It makes no sense. ; Because , After C ++ throws an exception , Just jump out of the line where the new operator is located.Code , Instead of executing subsequent code lines , So , The code for determining the return value of the new operator cannot be executed. ; Of course , The standard C ++ also provides methods to suppress exceptions thrown. , So that the exception of memory allocation failure is no longer ruled out , Returns a null pointer directly. , This is because there may be no exception handling mechanism in the old compiler. , Exceptions cannot be caught. ; For example:
Int * P = new int [size];
If (P = 0) // check if p is a null pointer;This judgment is meaningless.;
{
Return-1;
}
So,There are two methods in C ++ to handle the memory allocation failure error of the new operator.;
1. Capture the exception thrown by the new operator:
Char * P = NULL;
Try
{
P = new char [1024];
}
Catch (const STD: bad_alloc & Ex)
{
// Exception handle;
Return-1;
}
2. Suppress the exception throw:
char * P = NULL ;
P = new (STD: nothrow) Char [1024] ; // , if new memory allocation fails , No exception is thrown. , instead, a null pointer is returned. ;
If (P = NULL) // This judgment makes sense.;
{
// Error handle;
Return-1;
}
Original article:
Http://blog.csdn.net/app_12062011/article/details/7302673