Fix beningn GCC 10.2 Wstringop-truncation warnings
authorAndrey Alekseenko <al42and@gmail.com>
Thu, 22 Apr 2021 16:44:08 +0000 (18:44 +0200)
committerAndrey Alekseenko <al42and@gmail.com>
Fri, 23 Apr 2021 09:20:19 +0000 (09:20 +0000)
- `get_pdb_atomnumber`
  GCC was worried that we're copying up to 4 bytes to a buffer of
  length 4, not leaving the space for terminating \0. The source string
  is guaranteed to have length 3 + terminator, so not a problem.
  Changed to strcpy, since it should be safe here.
  While at it, renamed a variable, gave a name to a magic constant,
  added a static_assert to ensure safety.

- `read_vsite_database`
  GCC was complaining that we're copying 4094 bytes from a string of
  length 4094, possibly truncating the terminating \0. The string was
  guaranteed to have a terminator in its first 4093 bytes (fgets2 will
  put it no later than STRLEN-2, and we also skip the first character).
  But to make GCC happy, I see no harm in adding 1 more byte to strncpy.

Another warning from GCC is an actual error, fixed in MR !1487.

src/gromacs/fileio/pdbio.cpp
src/gromacs/gmxpreprocess/gen_vsite.cpp

index 3de2fddbcd1b28b7346a751bbf882b95fa727924..1b3c4ec0ca9caca148c44e34fc0cd1d3425d54ea 100644 (file)
@@ -575,18 +575,20 @@ void get_pdb_atomnumber(const t_atoms* atoms, AtomProperties* aps)
                 atomNumberSet = true;
             }
         }
-        std::string buf;
+        static constexpr size_t sc_maxElementNameLength = 3;
+        static_assert(sizeof(atoms->atom[i].elem) >= sc_maxElementNameLength + 1);
+        std::string element;
         if (atomNumberSet)
         {
             atoms->atom[i].atomnumber = atomnumber;
-            buf                       = aps->elementFromAtomNumber(atomnumber);
+            element                   = aps->elementFromAtomNumber(atomnumber);
             if (debug)
             {
                 fprintf(debug, "Atomnumber for atom '%s' is %d\n", anm, atomnumber);
             }
         }
-        buf.resize(3);
-        std::strncpy(atoms->atom[i].elem, buf.c_str(), 4);
+        element.resize(sc_maxElementNameLength);
+        std::strcpy(atoms->atom[i].elem, element.c_str());
     }
 }
 
index d94a14e58281182b50afbbddeadc3ade88689bb8..448b5de2fa47a2d78d95ed80fe1a265e22c304bf 100644 (file)
@@ -274,7 +274,7 @@ static void read_vsite_database(const char*                            ddbname,
         {
             if (pline[0] == OPENDIR)
             {
-                strncpy(dirstr, pline + 1, STRLEN - 2);
+                strncpy(dirstr, pline + 1, STRLEN - 1);
                 if ((ch = strchr(dirstr, CLOSEDIR)) != nullptr)
                 {
                     (*ch) = 0;