Hi folks,
I've spotted a possible bug in the main() routine of myserver.cpp. There's a
variable initialized via the "new" operator which is not in a try/catch
block and doesn't use the "nothrow" clause. This might lead to an uncaught
"bad_alloc" exception which would abort the execution of the server.

I'm attaching my proposed refactoring for the mentioned code.
bye ;)
From 5929e427a41c920b776403100284cb52475bd923 Mon Sep 17 00:00:00 2001
From: Daniele Cocca <[email protected]>
Date: Sat, 27 Mar 2010 20:26:34 +0100
Subject: [PATCH] Refactored the code which checks if MyServer has been called with an absolute path (extracted a method).

---
 myserver/src/myserver.cpp |   52 +++++++++++++++++---------------------------
 1 files changed, 20 insertions(+), 32 deletions(-)

diff --git a/myserver/src/myserver.cpp b/myserver/src/myserver.cpp
index dc487c3..9822b9d 100644
--- a/myserver/src/myserver.cpp
+++ b/myserver/src/myserver.cpp
@@ -348,6 +348,24 @@ int loadConfFilesLocation (string &mainConfigurationFile,
   return 0;
 }
 
+static void updateWorkingDirectory(const char *firstArgument)
+{
+  string path (firstArgument);
+  size_t index;
+
+#ifdef WIN32
+  index = path.find_last_of ('\\');
+#else
+  index = path.find_last_of ('/');
+#endif
+
+  if (index != string::npos)
+    {
+      string newdir (path, 0, index);
+      setcwd (newdir.c_str ());
+    }
+}
+
 static MainConfiguration *_genMainConf (Server *server, const char *arg)
 {
   XmlMainConfiguration *conf = new XmlMainConfiguration ();
@@ -397,38 +415,8 @@ int main (int argn, char **argv)
       return 1;
     };
 
-  u_int pathLen = 0;
-  u_int len = 0;
-  bool differentCwd = false;
-  char *path;
-
-  pathLen = strlen (argv[0]);
-  path = new char[pathLen + 1];
-  if (path == 0)
-    return 1;
-  strncpy (path, argv[0], pathLen);
-
-  for (len = 0; len < pathLen; len++)
-    {
-      if (path[len] == '/' || path[len] == '\\')
-        {
-          differentCwd = true;
-          break;
-        }
-    }
-
-  if (differentCwd)
-    {
-      len = pathLen;
-      while ((path[len] != '\\') && (path[len] != '/'))
-        len--;
-      path[len] = '\0';
-
-      setcwd (path);
-    }
-
-  /* We can free path memory now.  */
-  delete [] path;
+  /* Move to a different working directory, if necessary. */
+  updateWorkingDirectory (argv[0]);
 
   /* Call the parser.  */
   argp_parse (&myserverArgp, argn, argv, 0, 0, &input);
-- 
1.7.0.2

Reply via email to