Browse Source

cbuf: Fix memory leaks and reduce allocations.

Georgi Chorbadzhiyski 9 years ago
parent
commit
0ca91d9ef8
2 changed files with 10 additions and 12 deletions
  1. 9
    11
      cbuf.c
  2. 1
    1
      cbuf.h

+ 9
- 11
cbuf.c View File

17
 #include "cbuf.h"
17
 #include "cbuf.h"
18
 
18
 
19
 static void cbuf_lock(CBUF *b) {
19
 static void cbuf_lock(CBUF *b) {
20
-	pthread_mutex_lock(b->lock);
20
+	pthread_mutex_lock(&b->lock);
21
 }
21
 }
22
 
22
 
23
 static void cbuf_unlock(CBUF *b) {
23
 static void cbuf_unlock(CBUF *b) {
24
-	pthread_mutex_unlock(b->lock);
24
+	pthread_mutex_unlock(&b->lock);
25
 }
25
 }
26
 
26
 
27
 /* Returns how much data is filled in the buffer */
27
 /* Returns how much data is filled in the buffer */
54
 }
54
 }
55
 
55
 
56
 CBUF *cbuf_init(int buffer_size, char *name) {
56
 CBUF *cbuf_init(int buffer_size, char *name) {
57
-	CBUF *b = calloc(1, sizeof(CBUF));
58
-	if (!b)
59
-		return NULL;
60
 	if (!buffer_size)
57
 	if (!buffer_size)
61
 		return 0;
58
 		return 0;
62
-	pthread_mutex_t *mutex = malloc(sizeof(pthread_mutex_t));
63
-	if (pthread_mutex_init(mutex, NULL) != 0) {
59
+	CBUF *b = calloc(1, sizeof(CBUF));
60
+	if (!b)
61
+		return NULL;
62
+	if (pthread_mutex_init(&b->lock, NULL) != 0) {
64
 		perror("cbuf_new: mutex_init");
63
 		perror("cbuf_new: mutex_init");
64
+		free(b);
65
 		return NULL;
65
 		return NULL;
66
 	}
66
 	}
67
-	b->lock     = mutex;
68
 	b->name     = strdup(name);
67
 	b->name     = strdup(name);
69
 	b->size     = buffer_size;
68
 	b->size     = buffer_size;
70
 	b->pos      = 0;
69
 	b->pos      = 0;
71
 	b->writepos = 0;
70
 	b->writepos = 0;
72
 	b->buffer   = calloc(1, buffer_size);
71
 	b->buffer   = calloc(1, buffer_size);
73
 	if (!b->buffer) {
72
 	if (!b->buffer) {
74
-		free(b);
75
 		LOGf("CBUF  [%10s]: Can't allocate buffer size: %d\n", name, buffer_size);
73
 		LOGf("CBUF  [%10s]: Can't allocate buffer size: %d\n", name, buffer_size);
74
+		free(b);
76
 		return NULL;
75
 		return NULL;
77
 	}
76
 	}
78
 	return b;
77
 	return b;
82
 	CBUF *b = *pb;
81
 	CBUF *b = *pb;
83
 	if (!b)
82
 	if (!b)
84
 		return;
83
 		return;
85
-	pthread_mutex_destroy(b->lock);
86
-	FREE(b->lock);
84
+	pthread_mutex_destroy(&b->lock);
87
 	FREE(b->buffer);
85
 	FREE(b->buffer);
88
 	FREE(b->name);
86
 	FREE(b->name);
89
 	FREE(*pb);
87
 	FREE(*pb);

+ 1
- 1
cbuf.h View File

12
 
12
 
13
 // Circular buffer
13
 // Circular buffer
14
 typedef struct {
14
 typedef struct {
15
-	pthread_mutex_t *lock;
15
+	pthread_mutex_t lock;
16
 	char *name;
16
 	char *name;
17
 	int size;			/* Buffer size, must be (bufsize % 1316) == 0 */
17
 	int size;			/* Buffer size, must be (bufsize % 1316) == 0 */
18
 	int pos;			/* Up to where the buffer is filled */
18
 	int pos;			/* Up to where the buffer is filled */

Loading…
Cancel
Save