Fix pg_ctl's readfile() to not go into infinite loop on an empty file
authorTom Lane <tgl@sss.pgh.pa.us>
Wed, 2 Sep 2009 02:40:52 +0000 (02:40 +0000)
committerTom Lane <tgl@sss.pgh.pa.us>
Wed, 2 Sep 2009 02:40:52 +0000 (02:40 +0000)
(could happen if either postgresql.conf or postmaster.opts is empty).
It's been broken since the C version was written for 8.0, so patch
all the way back.

initdb's copy of the function is broken in the same way, but it's
less important there since the input files should never be empty.
Patch that in HEAD only, and also fix some cosmetic differences that
crept into that copy of the function.

Per report from Corry Haines and Jeff Davis.

src/bin/initdb/initdb.c
src/bin/pg_ctl/pg_ctl.c

index 4b0b72304bdac1a03e5715d6999c0efc0b5b74ce..b6998f36fd42bc41253d8053c96c5451f1691c2d 100644 (file)
@@ -149,7 +149,7 @@ static char **replace_token(char **lines,
 #ifndef HAVE_UNIX_SOCKETS
 static char **filter_lines_with_token(char **lines, const char *token);
 #endif
-static char **readfile(char *path);
+static char **readfile(const char *path);
 static void writefile(char *path, char **lines);
 static FILE *popen_check(const char *command, const char *mode);
 static int     mkdir_p(char *path, mode_t omode);
@@ -362,10 +362,10 @@ filter_lines_with_token(char **lines, const char *token)
  * get the lines from a text file
  */
 static char **
-readfile(char *path)
+readfile(const char *path)
 {
        FILE       *infile;
-       int                     maxlength = 0,
+       int                     maxlength = 1,
                                linelen = 0;
        int                     nlines = 0;
        char      **result;
@@ -394,26 +394,20 @@ readfile(char *path)
        }
 
        /* handle last line without a terminating newline (yuck) */
-
        if (linelen)
                nlines++;
        if (linelen > maxlength)
                maxlength = linelen;
 
        /* set up the result and the line buffer */
-
-       result = (char **) pg_malloc((nlines + 2) * sizeof(char *));
-       buffer = (char *) pg_malloc(maxlength + 2);
+       result = (char **) pg_malloc((nlines + 1) * sizeof(char *));
+       buffer = (char *) pg_malloc(maxlength + 1);
 
        /* now reprocess the file and store the lines */
-
        rewind(infile);
        nlines = 0;
        while (fgets(buffer, maxlength + 1, infile) != NULL)
-       {
-               result[nlines] = xstrdup(buffer);
-               nlines++;
-       }
+               result[nlines++] = xstrdup(buffer);
 
        fclose(infile);
        free(buffer);
index 08e38e7440a7383010817fdf405c7cc38a418791..dd1ce1a657f34615cbecc79d2eae23d6913fd577 100644 (file)
@@ -292,7 +292,7 @@ static char **
 readfile(const char *path)
 {
        FILE       *infile;
-       int                     maxlength = 0,
+       int                     maxlength = 1,
                                linelen = 0;
        int                     nlines = 0;
        char      **result;