From c092f4f7f8d0d391c11a1d26710549bc50d40c4c Mon Sep 17 00:00:00 2001 From: Stathis Kamperis Date: Sun, 29 Jul 2007 21:20:57 +0300 Subject: [PATCH] Fix possible memory leak when malloc() fails --- netbsd-llist.c | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/netbsd-llist.c b/netbsd-llist.c index eafc9b7..9e6d012 100644 --- a/netbsd-llist.c +++ b/netbsd-llist.c @@ -2,7 +2,6 @@ #include #include #include -#include LIST_HEAD(listhead, entry) head; struct listhead *headp; @@ -12,8 +11,6 @@ struct entry { const char *str; } *np, *n; -void diep(const char *s); - int main(void) { const char *str[] = { "this", "is", "a", "linked", "list" }; @@ -25,9 +22,10 @@ int main(void) /* Populate list with str[] items */ for (i = 0; i < sizeof str / sizeof *str; i++) { - n = malloc(sizeof(struct entry)); - if (n == NULL) - diep("malloc"); + if ((n = malloc(sizeof(struct entry))) == NULL) { + perror("malloc"); + goto CLEANUP_AND_EXIT; + } n->str = str[i]; if (i == 0) @@ -41,15 +39,10 @@ int main(void) LIST_FOREACH(np, &head, entries) printf("%s\n", np->str); + CLEANUP_AND_EXIT:; /* Delete all elements */ while (LIST_FIRST(&head) != NULL) LIST_REMOVE(LIST_FIRST(&head), entries); return EXIT_SUCCESS; } - -void diep(const char *s) -{ - perror(s); - exit(EXIT_FAILURE); -} -- 2.11.4.GIT