diff --git a/src/interfaces/ecpg/ecpglib/connect.c b/src/interfaces/ecpg/ecpglib/connect.c
index 71fa2753638..1e27238856f 100644
--- a/src/interfaces/ecpg/ecpglib/connect.c
+++ b/src/interfaces/ecpg/ecpglib/connect.c
@@ -484,6 +484,47 @@ ECPGconnect(int lineno, int c, const char *name, const char *user, const char *p
 	else
 		realname = NULL;
 
+	/*
+	 * Count options for the allocation done below (this may produce an
+	 * overestimate, it's ok).
+	 */
+	if (options)
+		for (i = 0; options[i]; i++)
+			if (options[i] == '=')
+				connect_params++;
+
+	if (user && strlen(user) > 0)
+		connect_params++;
+	if (passwd && strlen(passwd) > 0)
+		connect_params++;
+
+	/*
+	 * Allocate enough space for all connection parameters.  These allocations
+	 * are done before manipulating the list of connections to ease the error
+	 * handling on failure.
+	 */
+	conn_keywords = (const char **) ecpg_alloc((connect_params + 1) * sizeof(char *), lineno);
+	conn_values = (const char **) ecpg_alloc(connect_params * sizeof(char *), lineno);
+	if (conn_keywords == NULL || conn_values == NULL)
+	{
+		if (host)
+			ecpg_free(host);
+		if (port)
+			ecpg_free(port);
+		if (options)
+			ecpg_free(options);
+		if (realname)
+			ecpg_free(realname);
+		if (dbname)
+			ecpg_free(dbname);
+		if (conn_keywords)
+			ecpg_free(conn_keywords);
+		if (conn_values)
+			ecpg_free(conn_values);
+		free(this);
+		return false;
+	}
+
 	/* add connection to our list */
 #ifdef ENABLE_THREAD_SAFETY
 	pthread_mutex_lock(&connections_mutex);
@@ -514,40 +555,6 @@ ECPGconnect(int lineno, int c, const char *name, const char *user, const char *p
 			 options ? "with options " : "", options ? options : "",
 			 (user && strlen(user) > 0) ? "for user " : "", user ? user : "");
 
-	if (options)
-		for (i = 0; options[i]; i++)
-			/* count options */
-			if (options[i] == '=')
-				connect_params++;
-
-	if (user && strlen(user) > 0)
-		connect_params++;
-	if (passwd && strlen(passwd) > 0)
-		connect_params++;
-
-	/* allocate enough space for all connection parameters */
-	conn_keywords = (const char **) ecpg_alloc((connect_params + 1) * sizeof(char *), lineno);
-	conn_values = (const char **) ecpg_alloc(connect_params * sizeof(char *), lineno);
-	if (conn_keywords == NULL || conn_values == NULL)
-	{
-		if (host)
-			ecpg_free(host);
-		if (port)
-			ecpg_free(port);
-		if (options)
-			ecpg_free(options);
-		if (realname)
-			ecpg_free(realname);
-		if (dbname)
-			ecpg_free(dbname);
-		if (conn_keywords)
-			ecpg_free(conn_keywords);
-		if (conn_values)
-			ecpg_free(conn_values);
-		free(this);
-		return false;
-	}
-
 	i = 0;
 	if (realname)
 	{