snprintf vs. strcpy (etc.) in C

后端 未结 7 1815
长发绾君心
长发绾君心 2021-01-02 07:35

For doing string concatenation, I\'ve been doing basic strcpy, strncpy of char* buffers. Then I learned about the snprintf and friends

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 08:17

    As others did point out already: Do not use strncpy.

    • strncpy will not zero terminate in case of truncation.
    • strncpy will zero-pad the whole buffer if string is shorter than buffer. If buffer is large, this may be a performance drain.

    snprintf will (on POSIX platforms) zero-terminate. On Windows, there is only _snprintf, which will not zero-terminate, so take that into account.

    Note: when using snprintf, use this form:

    snprintf(buffer, sizeof(buffer), "%s", string);
    

    instead of

    snprintf(buffer, sizeof(buffer), string);
    

    The latter is insecure and - if string depends on user input - can lead to stack smashes, etc.

提交回复
热议问题