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 */
} |