Translations of this page?:

strncpy

Syntax:

    #include <cstring>
    char *strncpy( char *to, const char *from, size_t count );
    namespace std {
      using ::strncpy;
   }

The strncpy function copies at most count characters of from to the string to. If from has less than count characters, the remainder is padded with '\0' characters. The return value is the resulting string.

Warning: If you read the definition carefully, you will see that strncpy may not NULL terminate the resulting string! This is a surprise to many people, but it has a very good reason, and leads us to the idiomatic use of strncpy:

  #include <cstring>
  #include <cstdlib>
  int main(int argc, char *argv[]) {
    if (argc!=2) { return EXIT_FAILURE; }
    char buff[6];
    strncpy(buff, argv[1], sizeof(buff));
    // Here comes the idiomatic part, that
    // must not be missing from code using strncpy:
    if (buff[sizeof(buff)-1] != '\0') {
      // We have overflow.  You may decide to give an error:
      return EXIT_FAILURE;
      // or to truncate your string:
      buff[sizeof(buff)-1]='\0';
    }
    // but in any case, make sure that at this line
    // you string is NULL (zero) terminated!
  }

The use of strncpy in itself does not result in safer code. It has to be used correctly (as above), otherwise a later code, which assumes that a buffer of 6 may contain maximum 5 characters, will fail, and may fail in a way that results in a security risk (crash or worse).

An alternative way that always NULL-terminates the string is to use strncat:

  #include <cstring>
  #include <cstdlib>
  int main(int argc, char *argv[]) {
    if (argc!=2) { return EXIT_FAILURE; }
    char buff[6] = "";
    strncat(buff, argv[1], sizeof(buff)-1);
  }

Related Topics: memcpy, strchr, strcpy, strncat, strncmp

Another set of related (but non-standard) functions are strlcpy and strlcat.

 
• • • IndexRecent changesRSScc