How to get rid of “unsafe” warnings / errors in Visual Studio (strcpy, sprintf, strdup)

后端 未结 9 1507
臣服心动
臣服心动 2020-12-05 10:43

I\'m trying to get rid of some compiler warnings that say strcpy, sprintf, etc are unsafe. I get why they\'re unsafe, but I can\'t think of a good way to fix the code, in a

9条回答
  •  庸人自扰
    2020-12-05 11:09

    You do know how much to copy - you allocated space for it!

    Surely you wouldn't willingly copy more than the space you allocated?

    I would prefer to use a method that explicitly avoids buffer overruns by limiting the number of items copied. Back when I was a C programmer we used

    dest = malloc(len);         // note: where did we get len?
    if ( dest is null )  panic!  // note: malloc can fail
    strncpy(dest, src, len);
    dest[len-1] =0;
    

    This is slightly messy, and has been pointed out is using strncpy() a method which really was originally designed for fixed-width fields rather than strings. However it does ach

    There are methods such as strdup() and strlcpy() which may we help.

    My recommendations:

    1). Your target should not be to suppress warnings but to make the code robust.

    2). When copying strings you need to ensure these things:

    • Protect yourself from bad input, for example an unterminated or excessively long string.
    • Protect yourself from malloc failures,
    • Strongly prefer copies of counted numbers of characters to copying until we see a null
    • If you claim to build a string, then make abolsutely sure you null terminate it

    If strlcpy() is available in your environment then you could use it, otherwise why not write your own little utilityy function? Then if there are warnings in just that function you've localised then problem.

提交回复
热议问题