Browse Source

list: Fix memory leaks and reduce allocations.

Georgi Chorbadzhiyski 9 years ago
parent
commit
4a4a76b517
2 changed files with 16 additions and 16 deletions
  1. 15
    15
      list.c
  2. 1
    1
      list.h

+ 15
- 15
list.c View File

@@ -22,21 +22,22 @@
22 22
 #endif
23 23
 
24 24
 LIST *list_new(char *name) {
25
-	pthread_mutex_t *mutex = malloc(sizeof(pthread_mutex_t));
26
-	if (pthread_mutex_init(mutex,NULL) != 0) {
27
-		perror("list_new: mutex_init");
28
-		return NULL;
29
-	}
30 25
 	LIST *list = calloc(1, sizeof(LIST));
31 26
 	if (!list)
32 27
 		return NULL;
33
-	list->mutex = mutex;
28
+	LNODE *node = calloc(1, sizeof(LNODE));
29
+	if (!node) {
30
+		free(list);
31
+		return NULL;
32
+	}
33
+	if (pthread_mutex_init(&list->mutex,NULL) != 0) {
34
+		perror("list_new: mutex_init");
35
+		free(list);
36
+		free(node);
37
+		return NULL;
38
+	}
34 39
 	list->name = strdup(name);
35 40
 
36
-	LNODE *node = malloc(sizeof(LNODE));
37
-	if (!node)
38
-		return NULL;
39
-
40 41
 	node->data = NULL;
41 42
 	node->next = node;
42 43
 	node->prev = node;
@@ -64,18 +65,17 @@ void list_free(LIST **plist, void (*free_func)(void *), void (*freep_func)(void
64 65
 	}
65 66
 	FREE(list->head);
66 67
 	list_unlock(list);
67
-	pthread_mutex_destroy(list->mutex);
68
-	FREE(list->mutex);
68
+	pthread_mutex_destroy(&list->mutex);
69 69
 	FREE(list->name);
70 70
 	FREE(*plist);
71 71
 }
72 72
 
73 73
 void list_lock(LIST *list) {
74
-	pthread_mutex_lock(list->mutex);
74
+	pthread_mutex_lock(&list->mutex);
75 75
 }
76 76
 
77 77
 void list_unlock(LIST *list) {
78
-	pthread_mutex_unlock(list->mutex);
78
+	pthread_mutex_unlock(&list->mutex);
79 79
 }
80 80
 
81 81
 void list_add(LIST *list, void *data) {
@@ -89,7 +89,7 @@ void list_add(LIST *list, void *data) {
89 89
 		return;
90 90
 	}
91 91
 
92
-	LNODE *node = malloc(sizeof(LNODE));
92
+	LNODE *node = calloc(1, sizeof(LNODE));
93 93
 	if (!node) {
94 94
 		Ldbg(stderr, "list_add(%s), can't alloc node\n", list->name);
95 95
 		return;

+ 1
- 1
list.h View File

@@ -21,7 +21,7 @@ typedef struct LNODE {
21 21
 } LNODE;
22 22
 
23 23
 typedef struct LIST {
24
-	pthread_mutex_t *mutex;		// List's lock
24
+	pthread_mutex_t mutex;		// List's lock
25 25
 	struct LNODE *head;			// Points to first element of the list
26 26
 	struct LNODE *tail;			// Points to last element of the list
27 27
 	unsigned int items;			// How many items are in the list

Loading…
Cancel
Save