mersenneforum.org

mersenneforum.org (https://www.mersenneforum.org/index.php)
-   Software (https://www.mersenneforum.org/forumdisplay.php?f=10)
-   -   (patch) IniWriteFloat should limit its field width (https://www.mersenneforum.org/showthread.php?t=20503)

Explorer09 2015-09-23 01:02

(patch) IniWriteFloat should limit its field width
 
1 Attachment(s)
IniWriteFloat should limit its field width, otherwise it is easy to create a buffer overflow with a large floating point number. The syntax like sprintf(buf, "%f", num) is unsafe.

Ideally snprintf should be used instead of sprintf, but I assume not every system support that (it's C99, but some systems supports sprintf_s), and it takes time to write it in a backward-compatible way, so I guess I'll hold that for now and do it when I have more time.

However limiting the field width of float-to-string output always works.

The reverse functions, atof and strtod, always accept input in E notation.

[CODE]diff -r -u a/commonc.c b/commonc.c
--- a/commonc.c 2015-03-26 05:27:12.000000000 +0800
+++ b/commonc.c 2015-09-23 08:12:44.936980349 +0800
@@ -1745,8 +1745,10 @@
const char *keyword,
float val)
{
+ /* Assume FLT_MAX is 3.40282e+038, the maximum significant digits that
+ can be stored in this buf is 12. ((sizeof(buf))-sizeof("-.E+038")) */
char buf[20];
- sprintf (buf, "%f", val);
+ sprintf (buf, "%11g", val);
IniSectionWriteString (filename, section, keyword, buf);
}
[/CODE]


All times are UTC. The time now is 11:39.

Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2021, Jelsoft Enterprises Ltd.