---
# System prepended metadata

title: Ch07 Process Environment
tags: [APUE, C basics]

---

# Ch07 Process Environment
>###### tags: `APUE` `C basics`


### Potential Problem with Automatic Variable
```c=
#include <stdio.h>
#include <stdlib.h>

#define Datafile "data.txt"
#define buffer_size 100

FILE* open_data(void){
	FILE* fp;
	char data_buffer[buffer_size];
	if ((fp = fopen(Datafile,"r")) == NULL)
		return NULL;
	
	if (setvbuf(fp,data_buffer,_IOLBF,buffer_size) != 0)
		return NULL;
	
	printf("fp = %p\n",fp);
	int file_len = 0;	
	fseek(fp,0,SEEK_END);
	file_len = ftell(fp);
	fseek(fp,0,SEEK_SET);

	printf("file length %d\n",file_len);	
	return fp;
}
```



The basic rule is that an automatic variable can never be referenced after the function that declared it returns.The above code shows a function called open_data that opens a standard I/O stream and sets the buffering for the stream.

The problem is that when open_data returns, the space it used on the stack will be used by the stack frame for the next function that is called. But the standard I/O library will still be using that portion of memory for its stream buffer.Chaos is sure to result.

To correct this problem, **the array databuf needs to be allocated from global memory,either statically (static or extern) or dynamically (one of the alloc functions).**