diff --git a/src/config.c b/src/config.c
index 7c8f7cd66e8098bee17215797d36c62b4cf3812a..9006844aea141fbb0571c2752a46bbe8930a7edc 100644
--- a/src/config.c
+++ b/src/config.c
@@ -163,7 +163,8 @@ struct uci_package *uci_load_pkg(struct uci_context **ctx, const char *config)
 	}
 
 	if (uci_load(*ctx, config, &pkg) != UCI_OK) {
-		free(*ctx);
+		uci_free_context(*ctx);
+		*ctx = NULL;
 		return NULL;
 	}
 
@@ -1563,9 +1564,12 @@ int config_update(const char *confname, struct agent_config *cfg,
 	struct uci_element *e;
 
 	ctx = uci_alloc_context();
-	if (ctx && uci_load(ctx, confname, &pkg) != UCI_OK) {
+	if (!ctx)
+		return -1;
+
+	if (uci_load(ctx, confname, &pkg) != UCI_OK) {
 		dbg("config file '%s' not found!\n", confname);
-		free(ctx);
+		uci_free_context(ctx);
 		return -1;
 	}
 
@@ -1629,9 +1633,12 @@ int config_update2(const char *confname, struct agent_config *cfg,
 	struct uci_element *e;
 
 	ctx = uci_alloc_context();
-	if (ctx && uci_load(ctx, confname, &pkg) != UCI_OK) {
+	if (!ctx)
+		return -1;
+
+	if (uci_load(ctx, confname, &pkg) != UCI_OK) {
 		dbg("config file '%s' not found!\n", confname);
-		free(ctx);
+		uci_free_context(ctx);
 		return -1;
 	}