git » nmdb » commit 92436bf

nmdb: Improve handling of string options

author Alberto Bertogli
2010-05-03 18:55:30 UTC
committer Alberto Bertogli
2010-05-03 18:55:30 UTC
parent dfed7a8d45a31b76c874d3ec4436a4d78ea50475

nmdb: Improve handling of string options

This patch simplifies the handling of the string options, by using
strdup() instead of malloc()+strcpy(), and free()ing when appropriate
instead of leaking memory when the same option is passed more than once.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>

nmdb/main.c +18 -9

diff --git a/nmdb/main.c b/nmdb/main.c
index e784145..02df38a 100644
--- a/nmdb/main.c
+++ b/nmdb/main.c
@@ -71,12 +71,12 @@ static int load_settings(int argc, char **argv)
 	settings.foreground = 0;
 	settings.passive = 0;
 	settings.read_only = 0;
-	settings.logfname = "-";
+	settings.logfname = NULL;
 	settings.pidfile = NULL;
 	settings.backend = DEFAULT_BE;
 
-	settings.dbname = malloc(strlen(DEFDBNAME) + 1);
-	strcpy(settings.dbname, DEFDBNAME);
+	settings.dbname = strdup(DEFDBNAME);
+	settings.logfname = strdup("-");
 
 	while ((c = getopt(argc, argv,
 				"b:d:l:L:t:T:u:U:s:S:c:o:i:fprh?")) != -1) {
@@ -86,8 +86,7 @@ static int load_settings(int argc, char **argv)
 			break;
 		case 'd':
 			free(settings.dbname);
-			settings.dbname = malloc(strlen(optarg) + 1);
-			strcpy(settings.dbname, optarg);
+			settings.dbname = strdup(optarg);
 			break;
 
 		case 'l':
@@ -123,13 +122,13 @@ static int load_settings(int argc, char **argv)
 			break;
 
 		case 'o':
-			settings.logfname = malloc(strlen(optarg) + 1);
-			strcpy(settings.logfname, optarg);
+			free(settings.logfname);
+			settings.logfname = strdup(optarg);
 			break;
 
 		case 'i':
-			settings.pidfile = malloc(strlen(optarg) + 1);
-			strcpy(settings.pidfile, optarg);
+			free(settings.pidfile);
+			settings.pidfile = strdup(optarg);
 			break;
 
 		case 'f':
@@ -183,6 +182,14 @@ static int load_settings(int argc, char **argv)
 }
 
 
+static void free_settings()
+{
+	free(settings.dbname);
+	free(settings.logfname);
+	free(settings.pidfile);
+}
+
+
 int main(int argc, char **argv)
 {
 	struct cache *cd;
@@ -255,6 +262,8 @@ int main(int argc, char **argv)
 
 	unlink(settings.pidfile);
 
+	free_settings();
+
 	return 0;
 }