Avoid NULL pointer in C ++

Source: Internet
Author: User

I think the most common error during development is a null pointer.

I have been working for a while and have encountered many null pointers.

List list = dao. findById (id );
For (int I = 0; I <list. size (); I ++ ){
// Do some thing
}

If list = null, the use of the null pointer exceptionjava pointer array will appear.
The reason is not that List list = null but that of list. size (). If list is null, the size method cannot be used, so a null pointer error occurs.
In many cases, null pointer errors are similar to the above. Of course, they may often occur in multi-layer calls.
Therefore, it is generally necessary to process the return value.

List list = dao. findById (id );
If (list = null ){
// Generally, return processing is performed here to avoid the following statement from calling null. A null pointer occurs.
// Of course, you can also use the if else statement to skip statements that may contain null pointers.
}
If (list! = Null & list. size () <1 ){
// It must be noted that the content is empty and the content is null. if the content is empty, no null pointer is reported.
// But the for loop below is obviously not executed
}
For (int I = 0; I <list. size (); I ++ ){
// Do some thing
}
In addition, the empty pointer to the jsp page is the same, because jsp is compiled into a java class to run.
For example, the following code

<%
String para = ""
List list = request. getAttribute ("users ");

Log.info (para. length (); // output 0
// If list is null, a null pointer will also appear below
For (Iterator I = list. iterator (); I. hasNext ();){
// Output
}
%>


Excerpted from: a blog with a wall and grass

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.