Programming in Linux/Unix systems-errors that may occur during buffer settings

Source: Internet
Author: User
Linux/Unix System Programming-common Linux technology-Linux programming and kernel information-errors that may occur during buffer settings-the following is a detailed description. The following Program is an example I saw when I read "Advanced Programming for Unix environment (version 2)". It is very meaningful. This memory control error is intended for beginners, even some veterans will show up, so I will share it with you and remind you to pay attention to it.

The problem is that when open_data returns, the stack space it occupies will be released for the next function call. However, the standard I/O library still uses this buffer. Chaos will inevitably lead to errors. To correct the problem, we should declare the databuf variable as global, static, or extern, or use the alloc function to allocate space.
CODE:/* Incoorect usage of an automatic variable */
# Include

# Define DATAFILE "datafile"

FILE * open_data (void ){
FILE * fp;
Char databuf [BUFSIZ];/* setvbuf makes this the stdio buffer */

If (fp = fopen (DATAFILE, "r") = NULL)
Return (NULL );
If (setvbuf (fp, databuf, _ IOLBF, BUFSIZ )! = 0)
Return (NULL );

Return fp;/* error */
}

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.