if (*base == NULL) {
                /* Branch level */
                if (index < 8) {
-                       *base = malloc(sizeof(struct branch));
+                       if ((*base = malloc(sizeof(struct branch))) == NULL) {
+                               perror("Malloc failed");
+                               exit(EXIT_FAILURE);
+                       }
                        ((struct branch *)*base)->key = key[index] - ZERO_OFFSET;
                        ((struct branch *)*base)->next = NULL;
                        ((struct branch *)*base)->child = NULL;
                        ret = lookupLeaf(&(((struct branch *)*base)->child), key, index + 1);
                /* Leaf level */
                } else {
-                       *base = malloc(sizeof(struct leaf));
+                       if ((*base = malloc(sizeof(struct leaf))) == NULL) {
+                               perror("Malloc failed");
+                               exit(EXIT_FAILURE);
+                       }
                        ((struct leaf *)*base)->key = key[index] - ZERO_OFFSET;
                        ((struct leaf *)*base)->next = NULL;
                        ((struct leaf *)*base)->count = 0;
                                        /* Backup current in prev */
                                        prev = current;
                                        /* Create new branch with key */
-                                       current = malloc(sizeof(struct branch));
+                                       if ((current = malloc(sizeof(struct branch))) == NULL) {
+                                               perror("Malloc failed");
+                                               exit(EXIT_FAILURE);
+                                       }
                                        ((struct branch *)current)->key = key[index] - ZERO_OFFSET;
                                        ((struct branch *)current)->next = NULL;
                                        ((struct branch *)current)->child = NULL;
                                        /* Backup current in prev */
                                        prev = current;
                                        /* Create new leaf with key */
-                                       current = malloc(sizeof(struct leaf));
+                                       if ((current = malloc(sizeof(struct leaf))) == NULL) {
+                                               perror("Malloc failed");
+                                               exit(EXIT_FAILURE);
+                                       }
                                        ((struct leaf *)current)->key = key[index] - ZERO_OFFSET;
                                        ((struct leaf *)current)->next = NULL;
                                        ((struct leaf *)current)->count = 0;