An example of a helpful comment

An example of a helpful comment







Good programming books say that code should be self-documenting. And comments are needed where something non-trivial is being done. Our team shares this opinion, and recently we came across a piece of code that perfectly demonstrates this.







The code that we will look at next was written out in the course of work on the article " Date Handling Attracts Errors or 77 Defects in Qt 6 ".







The PVS-Studio analyzer drew attention to this code fragment, issuing a warning: V575 [CWE-628] The 'memcpy' function doesn't copy the whole string. Use 'strcpy / strcpy_s' function to preserve terminal null. qplaintestlogger.cpp 253. Actually, here it is:







const char *msgFiller = msg[0] ? " " : "";
QTestCharBuffer testIdentifier;
QTestPrivate::generateTestIdentifier(&testIdentifier);
QTest::qt_asprintf(&messagePrefix, "%s: %s%s%s%s\n",
                   type, testIdentifier.data(), msgFiller, msg,
                   failureLocation.data());

// In colored mode, printf above stripped our nonprintable control characters.
// Put them back.
memcpy(messagePrefix.data(), type, strlen(type));

outputMessage(messagePrefix.data());
      
      





Notice the call to the memcpy function . By itself, this code raises two questions at once:







  1. Why is something being written to a buffer whose contents have just been generated using a printf-like function?
  2. Certainly not a mistake that terminal zero is not copied? This is exactly what the analyzer does not like.


, . .







. , . .







:







char buf[1024];

if (result.setByMacro) {
  qsnprintf(buf, sizeof(buf), "%s%s%s%s%s%s\n", buf1, bufTag, fill,
            buf2, buf2_, buf3);
} else {
  qsnprintf(buf, sizeof(buf), "%s%s%s%s\n", buf1, bufTag, fill, buf2);
}

memcpy(buf, bmtag, strlen(bmtag));
outputMessage(buf);
      
      





. . , . , memcpy. , , buf1, bmtag. , . .







, : Andrey Karpov. One Useful Comment.








All Articles