What makes a C standard library function dangerous, and what is the alternative?

前端 未结 9 879
广开言路
广开言路 2020-12-04 06:05

While learning C I regularly come across resources which recommend that some functions (e.g. gets()) are never to be used, because they are either difficult or

9条回答
  •  Happy的楠姐
    2020-12-04 06:34

    In the old days, most of the string functions had no bounds checking. Of course they couldn't just delete the old functions, or modify their signatures to include an upper bound, that would break compatibility. Now, for almost every one of those functions, there is an alternative "n" version. For example:

    strcpy -> strncpy
    strlen -> strnlen
    strcmp -> strncmp
    strcat -> strncat
    strdup -> strndup
    sprintf -> snprintf
    wcscpy -> wcsncpy
    wcslen -> wcsnlen
    

    And more.

    See also https://github.com/leafsr/gcc-poison which is a project to create a header file that causes gcc to report an error if you use an unsafe function.

提交回复
热议问题