Rewrite get_string to fix a buffer overflow and check a few special cases
authorparasti <parasti@78b8d119-cf0a-0410-b17c-f493084dd1d7>
Fri, 12 Jun 2009 00:15:59 +0000 (00:15 +0000)
committerparasti <parasti@78b8d119-cf0a-0410-b17c-f493084dd1d7>
Fri, 12 Jun 2009 00:15:59 +0000 (00:15 +0000)
git-svn-id: https://s.snth.net/svn/neverball/trunk@2872 78b8d119-cf0a-0410-b17c-f493084dd1d7

share/binary.c

index 1ada5ed..3cd1de1 100644 (file)
@@ -142,12 +142,24 @@ void put_string(FILE *fout, const char *s)
 
 void get_string(FILE *fin, char *s, int max)
 {
-    do
-        *s = (char) fgetc(fin);
-    while (*s++ != '\0' && max-- > 0);
+    int c = -1;
 
-    if(*(s - 1) != '\0')
-        *(s - 1) = '\0';
+    if (max == 0)
+        return;
+
+    while (max && c && (c = fgetc(fin)) != EOF)
+    {
+        *s++ = c;
+        max--;
+    }
+
+     /*
+      * Terminate the buffer ourselves, if we ran out of space without
+      * seeing a NUL character.
+      */
+
+    if (max == 0 && *(s - 1) != 0)
+        *(s - 1) = 0;
 }
 
 /*---------------------------------------------------------------------------*/