我写了一个程序,但是我发现它有内存泄漏,经过几次迭代后,它出现了段错误。我不明白这个内存泄漏在哪里。
下面是整个代码片段。我知道代码存在常规错误,例如全局分配和制作比需要大得多的缓冲区。我只是看不到泄漏的来源。
提前致谢。
#include <stdlib.h>
#include <stdio.h>
#define DATA 1000
#define TRUE 1
#define FALSE 0
const int16_t TIME = 600; // Time in seconds.
const int8_t DEBUG = 0;
// Globals Because I'm lazy!
long int cpua[5];
long int cpub[5];
long int mema[2];
long int nets[2];
long int netr[2];
int k=0;
char ch[150];
FILE *file_read;
char buffer[DATA];
void CPUread(void){
file_read = popen("cat /proc/stat | grep \"cpu \"","r");
fgets(buffer, DATA, file_read);
sscanf(buffer,"%s %ld %ld %ld %ld %ld",&ch[0],&cpua[0],&cpua[1],&cpua[2],&cpua[3],&cpua[4]);
// Time to read the network..
file_read = popen("ifconfig | grep -m 1 \"RX bytes:\" | awk -F \"[^0-9]*\" '{ print $2 }'","r");
fgets(buffer, DATA, file_read);
sscanf(buffer,"%ld",&netr[0]);
file_read = popen("ifconfig | grep -m 1 \"RX bytes:\" | awk -F \"[^0-9]*\" '{ print $5 }'","r");
fgets(buffer, DATA, file_read);
sscanf(buffer,"%ld",&nets[0]);
// Time to read memory
file_read = popen("cat /proc/meminfo | grep -m 1 \"MemFree\" | awk -F \"[^0-9]*\" '{ print $2 }'","r");
fgets(buffer, DATA, file_read);
sscanf(buffer,"%ld",&mema[0]);
file_read = popen("cat /proc/meminfo | grep -m 1 \"MemTotal\" | awk -F \"[^0-9]*\" '{ print $2 }'","r");
fgets(buffer, DATA, file_read);
sscanf(buffer,"%ld",&mema[1]);
}
void main(void){
FILE *file_write, *fp;
int i;
long int total=0, ptotal=0;
int valid = FALSE;
char charbuf[100];
file_write=popen("echo -n \"/var/www/dir/`date +%Y-%b-%d`.csv\"","r");
fgets(charbuf,100, file_write);
while(1){
// Open up the status file container and read from the system.
if(valid == FALSE ){
CPUread();
// Need to make a new file here.... With Date code.
fp=fopen(charbuf,"a");
if ( fp == NULL){
perror("Dummy Spit In initial File create!\n");
exit(-1);
}
fprintf(fp,"CPU,IOwait,Memory,KB_up,KB_down\n");
if(DEBUG) printf("CPU,IOwait,Memory,KB_up,KB_down\n");
valid = TRUE;
fclose(fp);
}else{
for(i=0;i<5;i++) cpub[i] = cpua[i];
nets[1]=nets[0];
netr[1]=netr[0];
CPUread();
total = 0;
for(i=0;i<5;i++){
cpub[i]=cpua[i]-cpub[i];
total+=cpub[i];
}
// Time to find the CPU useage and IO waits...
fp=fopen(charbuf,"a");
if ( fp == NULL){
perror("Dummy Spit Trying to open file\n");
exit(-1);
}
fprintf(fp,"%0.2f,%0.2f,%0.2f,%ld,%ld\n",(((float)cpub[0])/total)*100,(((float)cpub[4]/total)*100),((((float)mema[1]-(float)mema[0])/(float)mema[1]))*100,(nets[0]-nets[1])/1024,(netr[0]-netr[1])/1024);
if(DEBUG) printf("%0.2f,%0.2f,%0.2f,%ld,%ld\n",(((float)cpub[0])/total)*100,(((float)cpub[4]/total)*100),((((float)mema[1]-(float)mema[0])/(float)mema[1]))*100,(nets[0]-nets[1])/1024,(netr[0]-netr[1])/1024);
fclose(fp);
}
sleep(TIME);
}
}