[PATCH:xman 4/4] Use snprintf to PATH_MAX sized buffers to construct filenames

Alan Coopersmith alan.coopersmith at oracle.com
Fri Jan 28 23:14:00 PST 2011


Simpler than trying to calculate the size to malloc.

Could have used XtAsprintf() but didn't seem worth the dependency
for two simple calls with a standard, well-known maximum size.

Signed-off-by: Alan Coopersmith <alan.coopersmith at oracle.com>
---
 main.c |    6 +++---
 misc.c |   11 +++--------
 2 files changed, 6 insertions(+), 11 deletions(-)

diff --git a/main.c b/main.c
index c709d5e..1b6f8e9 100644
--- a/main.c
+++ b/main.c
@@ -285,12 +285,12 @@ AdjustDefResources(void)
 
   for (i = 0; i < sizeof(my_resources)/sizeof(XtResource); i++) {
     if (!strcmp(my_resources[i].resource_name, "helpFile")) {
-      if (!(my_resources[i].default_addr =
-              malloc(strlen(xwinhome) + sizeof("/lib/X11/xman.help")))) {
+      char filename[PATH_MAX];
+      snprintf(filename, sizeof(filename), "%s/lib/X11/xman.help", xwinhome);
+      if (!(my_resources[i].default_addr = strdup(filename))) {
         fprintf(stderr, "malloc failure\n");
         exit(EXIT_FAILURE);
       }
-      sprintf(my_resources[i].default_addr, "%s/lib/X11/xman.help", xwinhome);
     }
   }
 }
diff --git a/misc.c b/misc.c
index 0921307..8818aa8 100644
--- a/misc.c
+++ b/misc.c
@@ -693,7 +693,7 @@ ConstructCommand(cmdbuf, path, filename, tempfile)
    FILE *file;
    char fmtbuf[128];
    int gotfmt = 0;             /* set to 1 if we got a directive from source */
-   char *fname = NULL;
+   char fname[PATH_MAX];
 #ifdef __UNIXOS2__
    int i;
 #endif
@@ -708,12 +708,9 @@ ConstructCommand(cmdbuf, path, filename, tempfile)
        * use system to get the thing to a known absoute filename.
        */
       if (filename[0] == '/') {
-         fname = filename;
+         snprintf(fname, sizeof(fname), "%s", filename);
       } else {
-         fname = malloc(strlen(path) + 1 + strlen(filename) + 1);
-         if (!fname)
-            return FALSE;
-         sprintf(fname, "%s/%s", path, filename);
+         snprintf(fname, sizeof(fname), "%s/%s", path, filename);
       }
       if ((file = fopen(fname, "r")) &&
           (fgets(fmtbuf, sizeof(fmtbuf), file)) &&
@@ -727,8 +724,6 @@ ConstructCommand(cmdbuf, path, filename, tempfile)
             gotfmt++;
          }
       }
-      if (fname && fname != filename)
-         free(fname);
       if (!gotfmt)                                /* not there or some error */
       {
          fmt = getenv("MANROFFSEQ");
-- 
1.7.3.2



More information about the xorg-devel mailing list