C language memory allocation is a bad habit that is easily overlooked.

Source: Internet
Author: User

Take a look at this sectionCode.

P = Malloc (bytes );
If (P = Null)
... {
Printf ("Can't allocate enough memory.");
Return 0;
}

 

On the surface, this is very good, considering the insufficient memory allocation is an error. But there is a problem: imagine that when it takes several hours to process a document, your favorite text processing period suddenly tries to allocate 20 or 30 bytes to a new font instance, the result allocation fails, and an explanation is written to stdout, and the processing is terminated. I have no chance to cancel the operation that causes the memory allocation request. I have no choice to save my work. I have been working for an hour.

 

This is an example in the Standard C language book. Maybe with the virtual memory technology, we don't have to worry about the memory insufficiency error when applying for a new memory. So such judgment will never be executed.ProgramCan run, get the correct result. So we think there is no problem. But in the face of other exceptions, do we have to deal with them in the same wrong way. For example, if an error occurs, you can immediately exit the program, and at most, you will be prompted about the error. But have we considered the problem from the user's perspective? What should we do with the data they are processing? This mindset is sometimes terrible.

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.