Adjusted real2string
authorJoey Schulze <joey@infodrom.org>
Sat, 30 Aug 2003 08:53:28 +0000 (08:53 +0000)
committerJoey Schulze <joey@infodrom.org>
Sat, 30 Aug 2003 08:53:28 +0000 (08:53 +0000)
 . ensure no overflow
 . don't fail when string is too short
 . don't copy random characters but only digits
Adjusted copyright notice

dtaus.c

diff --git a/dtaus.c b/dtaus.c
index bc332f8..dcb69fc 100644 (file)
--- a/dtaus.c
+++ b/dtaus.c
@@ -1,6 +1,6 @@
 /*
     dtaus.c - Belegloser Datenträgeraustausch mit einer Bank
 /*
     dtaus.c - Belegloser Datenträgeraustausch mit einer Bank
-    Copyright (c) 1996,8,2001,2  Martin Schulze <joey@infodrom.org>
+    Copyright (c) 1996,8,2001,2,3  Martin Schulze <joey@infodrom.org>
 
     This program is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
 
     This program is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
@@ -274,10 +274,36 @@ char *real2string(char *s)
   static char res[20];
   char *cp;
 
   static char res[20];
   char *cp;
 
-  strcpy(res, s);
+  strncpy(res, s, sizeof(res)-1);
+  res[sizeof(res)-1] = 0;
   for (cp=res; *cp&&!(*cp == ',')&&!(*cp == '.');cp++);
   for (cp=res; *cp&&!(*cp == ',')&&!(*cp == '.');cp++);
-  *(cp++) = *(cp+1);
-  *(cp++) = *(cp+1);
+
+  if ((cp-res) >= (sizeof(res)-3)) { 
+    /* Bail out, since the number is too large, shouldn't be possible though. */
+    fprintf (stderr, "Value %s too large.\n", res);
+    exit (1);
+  }
+
+  if (*cp == '.' || *cp == ',') {
+    if (*(cp+1)) {
+      /* 1st decimal place */
+      if (isdigit(*(cp+1)))
+       *(cp++) = *(cp+1);
+      else
+       *(cp++) = '0';
+      /* 2nd decimal place */
+      if (*(cp+1) && isdigit(*(cp+1)))
+       *(cp++) = *(cp+1);
+      else
+       *(cp++) = '0';
+    } else {
+      *(cp++) = '0';
+      *(cp++) = '0';
+    }
+  } else {
+    *(cp++) = '0';
+    *(cp++) = '0';
+  }
   *cp = '\0';
   return res;
 }
   *cp = '\0';
   return res;
 }