Search code examples
c++static-code-analysisstrncpycppcheck

cppcheck - terminateStrncpy


New to cppcheck. Couldn't figure out how to solve this issue (cppcheck warning). any help would be appreciated.

 if (!call_initialized)
 { char id1[16];
   char id1[16];
   char* dummy_char_ptr = inet_ntoa(*((in_addr*)&source_ip));
   std::strncpy(id1, dummy_char_ptr, 16);
   dummy_char_ptr=inet_ntoa(*((in_addr*)&destination_ip));
   std::strncpy(id2, dummy_char_ptr, 16);
   dummy_char_ptr=NULL;
   std::cerr << id1 << " -----> " << id2 << std::endl;
   return 0;
   }

error(warning) - The buffer 'id2' may not be zero-terminated after the call to strncpy().


Solution

  • Don't use strncpy (unless you really know what you're doing).

    strncpy(dst, src, n) always writes exactly n bytes. If src does not have a NUL byte in its first n bytes, no NUL byte will be written to dst, so you can turn a valid NUL-terminated string into an unterminated string (which is why you get the warning). If src is shorter than n bytes, strncpy will add NUL bytes to the end, which is usually unnecessary.

    Personally, I would use strdup (and remember to free the resulting copy when I'm done with it), because it is easier. strdup is a Posix extension to standard C library, but it's easy to write if you need it, and it exists on most platforms (as _strdup on Windows, iirc). Alternatively, you could strncpy one fewer byte than the size of your buffer, and then add a NUL at the end, or you could just check the length of the source string with strlen and fail if it is too long.