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
 #endif
22
 #endif
23
 
23
 
24
 LIST *list_new(char *name) {
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
 	LIST *list = calloc(1, sizeof(LIST));
25
 	LIST *list = calloc(1, sizeof(LIST));
31
 	if (!list)
26
 	if (!list)
32
 		return NULL;
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
 	list->name = strdup(name);
39
 	list->name = strdup(name);
35
 
40
 
36
-	LNODE *node = malloc(sizeof(LNODE));
37
-	if (!node)
38
-		return NULL;
39
-
40
 	node->data = NULL;
41
 	node->data = NULL;
41
 	node->next = node;
42
 	node->next = node;
42
 	node->prev = node;
43
 	node->prev = node;
64
 	}
65
 	}
65
 	FREE(list->head);
66
 	FREE(list->head);
66
 	list_unlock(list);
67
 	list_unlock(list);
67
-	pthread_mutex_destroy(list->mutex);
68
-	FREE(list->mutex);
68
+	pthread_mutex_destroy(&list->mutex);
69
 	FREE(list->name);
69
 	FREE(list->name);
70
 	FREE(*plist);
70
 	FREE(*plist);
71
 }
71
 }
72
 
72
 
73
 void list_lock(LIST *list) {
73
 void list_lock(LIST *list) {
74
-	pthread_mutex_lock(list->mutex);
74
+	pthread_mutex_lock(&list->mutex);
75
 }
75
 }
76
 
76
 
77
 void list_unlock(LIST *list) {
77
 void list_unlock(LIST *list) {
78
-	pthread_mutex_unlock(list->mutex);
78
+	pthread_mutex_unlock(&list->mutex);
79
 }
79
 }
80
 
80
 
81
 void list_add(LIST *list, void *data) {
81
 void list_add(LIST *list, void *data) {
89
 		return;
89
 		return;
90
 	}
90
 	}
91
 
91
 
92
-	LNODE *node = malloc(sizeof(LNODE));
92
+	LNODE *node = calloc(1, sizeof(LNODE));
93
 	if (!node) {
93
 	if (!node) {
94
 		Ldbg(stderr, "list_add(%s), can't alloc node\n", list->name);
94
 		Ldbg(stderr, "list_add(%s), can't alloc node\n", list->name);
95
 		return;
95
 		return;

+ 1
- 1
list.h View File

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

Loading…
Cancel
Save