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

+ 1
- 1
cbuf.h View File

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

Loading…
Cancel
Save