Cppcheck - terminateStrncpy

New to cppcheck. Couldn't figure out how to fix 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);
   std::strncpy(id2, dummy_char_ptr, 16);
   std::cerr << id1 << " -----> " << id2 << std::endl;
   return 0;


error (warning). Buffer "id2" cannot be zero-terminated after calling strncpy ().


source to share

1 answer

Don't use strncpy

(unless you really know what you are doing).

strncpy(dst, src, n)

always writes exactly n

bytes. If it src

doesn't have a byte NUL

in its first bytes n

, the byte NUL

won't be written to dst

, so you can turn a valid null-terminated string into a non-terminating string (which is why you get the warning). If src

shorter than n

bytes, strncpy

add bytes to the end NUL

, which is usually unnecessary.

Personally, I would use strdup

(and remember the free

resulting copy when I'm done with it) because it's easier. strdup

is a Posix extension to the C standard library, but is easy to write if you need it, and it exists on most platforms (like _strdup

Windows, iirc). Also, you can strncpy one byte than your buffer size and then add NUL at the end, or just check the length of the original string with strlen

and fail if it's too long.



All Articles