The security analysis of the C language new Operation _c language

Source: Internet
Author: User

For a friend who has learned C, you should know that when using a function such as malloc/calloc, it is important to check whether the return value is a "null pointer" (that is, to check whether the allocated memory is successful), which is good programming practice and necessary to write a reliable program. However, if you simply apply this trick to new, it may not be correct. I often see code similar to this:

int * p = new int [MAXSIZE]
if (p = = 0)//Check whether the P pointer is an empty
return-1;
Other code

In fact, the IF (p = = 0) Here is completely meaningless. In C + +, if new allocates memory failure, the default is to throw an exception. So, if the assignment succeeds, p = 0 will never set up, and if the allocation fails, it will not execute if (p = = 0), because when the allocation fails, new throws an exception to skip the following code. If you want to check whether 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 null pointers without throwing an exception.

int * p = new (std::nothrow) int [MAXSIZE]
if (p = = 0)//Check whether the P pointer is empty
return-1;
Other code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.