我正在做一个库来实现一个双缓冲区,基本的想法是我将需要缓冲区,一个将被写入而另一个读取,并且每次写入缓冲区变满时它们都会交换。 当我交换缓冲区并从valgrind获取时,我一直有内存泄漏:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include"data_structures.h"
#define BUFFER_SIZE 4000
typedef enum {firstBuf, secondBuf} currentBuf;
typedef struct {
char *buffer1;
char *buffer2;
currentBuf current;
int index;
} double_buffer;
pthread_cond_t buffer_cheio = PTHREAD_COND_INITIALIZER;
pthread_cond_t buffer_vazio = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex;
double_buffer *build_double_buffer(){
double_buffer *db = (double_buffer *)malloc(sizeof(double_buffer));
db->buffer1 = (char *)calloc(BUFFER_SIZE, sizeof(char));
db->buffer2 = (char *)calloc(BUFFER_SIZE, sizeof(char));
db->buffer1[0] = '\0';
db->buffer2[0] = '\0';
db->index = 0;
pthread_mutex_init(&mutex, NULL);
db->current = firstBuf;
return db;
}
void setDoubleBuffer(double_buffer *db, char *info){
pthread_mutex_lock(&mutex);
int len = strlen(info)+1;
if(db->index + len > BUFFER_SIZE){
switch(db->current){
case firstBuf:
while(db->buffer2[0] != '\0'){
pthread_cond_wait(&buffer_vazio, &mutex);
}
break;
case secondBuf:
while(db->buffer1[0] != '\0'){
pthread_cond_wait(&buffer_vazio, &mutex);
}
}
swapBuffer(db);
}
if(db->current == firstBuf){
if(!(db->index + len > BUFFER_SIZE)){
strcat(db->buffer1, info);
}else{
printf("erro");
}
}else{
if(!(db->index + len > BUFFER_SIZE)){
strcat(db->buffer2, info);
}else{
printf("erro");
}
}
db->index += len;
pthread_cond_signal(&buffer_cheio);
pthread_mutex_unlock(&mutex);
}
void swapBuffer(double_buffer *db){
int i;
char *buf1;
char *buf2;
if(db->current == firstBuf) {
buf1 = db->buffer1;
buf2 = db->buffer2;
} else {
buf2 = db->buffer1;
buf1 = db->buffer2;
}
for(i = 0; i < BUFFER_SIZE -1 || buf1[i] == '\0'; i++){ //line 85
buf2[i] = buf1[i]; //line 86
}
buf1[0] ='\0';
db->index = 0;
if(db->current == firstBuf){
db->current = secondBuf;
}else{
db->current = firstBuf;
}
}
void get_buffer(char *receiveBuffer, double_buffer *db){
pthread_mutex_lock(&mutex);
int i;
while(db->buffer1[0] == '\0' || db->buffer2[0] == '\0'){
pthread_cond_wait(&buffer_cheio, &mutex);
}
if(db->current == firstBuf){
for(i = 0; i < BUFFER_SIZE || db->buffer2[i] == '\0'; i++){
receiveBuffer[i] = db->buffer2[i];
}
db->buffer2[0] = '\0';
}else{
for(i = 0; i < BUFFER_SIZE || db->buffer1[i] == '\0'; i++){
receiveBuffer[i] = db->buffer1[i];
}
db->buffer1[0] = '\0';
}
pthread_cond_signal(&buffer_vazio);
pthread_mutex_unlock(&mutex);
}
我一直在尝试让它工作,但我无法看到我在做内存泄漏的地方而不是如何解决它。 代码如下:
//main thread before creating the threads
log_buffer = build_double_buffer();
//temparature thread
while(1){
char *log_string = NULL;
log_string = (char *)malloc(sizeof(char)*MAX_BUFFER_SIZE);
//code that calculates T
sprintf(log_string, "Temperura: %f\n", T);
setDoubleBuffer(log_buffer, log_string);
}
调用它的代码是:
{{1}}