C language new operation security analysis

  • 2020-04-02 02:24:03
  • OfStack

For those of you who have studied the C language, it is good programming practice and necessary to write reliable programs to make sure that when using functions such as malloc/calloc that allocate memory, you must check whether the return value is a "null pointer" (that is, whether the operation of allocating memory is successful). However, if you simply apply this trick to new, it may not be true. I often see code like this:


int * p = new int [MAXSIZE]
if (p == 0) //Check that the p pointer is null
return -1;
//other code

In fact, the if (p == 0) here is completely meaningless. In C++, if new allocation fails, an exception is thrown by default. So, if the distribution is successful, p == 0 will never be true; If the allocation fails, the if (p == 0) will not be executed, because if the allocation fails, new will throw an exception and skip the rest of the code. If you want to check if new is successful, you should catch the exception:


try
{
int * p = new int [MAXSIZE]
}
catch( bad_alloc & exp)
{
cerrr<<exp.what()<<endl;
}

But some programmers are not used to catching exceptions, and standard C++ provides a way to return a null pointer without throwing an exception.


int * p = new (std::nothrow)int [MAXSIZE]
if (p == 0) //Check that the p pointer is null
return -1;
//other code


Related articles: