Thread: Use strcpy safely

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    159

    Use strcpy safely

    Hi,
    I was wondering how to use strcpy safely so that I can get reported when overwriting happens?
    Or other methods that achieve the same function with security check?
    Also in C++, is there a C++ way to handle it besides using STL string class?

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    If you are not using a smart container like std::string, then the only way to be safe is to ensure that there is enough space before you do the copy. This means using strncpy(), or erroring out if the buffer is too small.

  3. #3
    Banned ಠ_ಠ's Avatar
    Join Date
    Mar 2009
    Posts
    687
    Quote Originally Posted by bithub View Post
    std::string
    I do not think you are where you think you are
    ╔╗╔══╦╗
    ║║║╔╗║║
    ║╚╣╚╝║╚╗
    ╚═╩══╩═╝

  4. #4
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    Moved to C++

  5. #5
    Registered User
    Join Date
    Jan 2009
    Posts
    159
    Thanks!

    Quote Originally Posted by bithub View Post
    erroring out if the buffer is too small.
    How to detect if the buffer is too small for strcpy()?

  6. #6
    The larch
    Join Date
    May 2006
    Posts
    3,573
    If you have established that you have enough room, why should you use strncpy?

    In C++, you can also use a std::vector<char> to take care of dynamic memory management for an otherwise C-style string (and knowing at any time how much memory you have for the buffer).

    How to detect if the buffer is too small for strcpy()?
    Unless you know how much memory is allocated for the target, there is no way. std::vector<char> helps in storing the size of the buffer for you.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  7. #7
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    How to detect if the buffer is too small for strcpy()?
    Usually this is pretty easy:
    Code:
    void do_copy(char* str)
    {
        char buffer[BUFFER_SIZE];
        size_t size = strlen(str);
        if(size >= BUFFER_SIZE)
        {
            /* Error, buffer is too small */
        }
        else
        {
            strcpy(buffer, str);
        }
        // ...
    }

  8. #8
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Quote Originally Posted by lehe View Post
    Hi,
    I was wondering how to use strcpy safely so that I can get reported when overwriting happens?
    Or other methods that achieve the same function with security check?
    Also in C++, is there a C++ way to handle it besides using STL string class?
    Is there a compelling reason to not use string or vector<char>?

  9. #9
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Location
    Banks of the River Styx
    Posts
    902
    If you're in C++, use std::string, as others have mentioned. If you absolutely must use strcpy(), just don't pass it a buffer that can't hold what you're going to copy into it. And don't forget about strdup(). Otherwise, it's generally:
    Code:
    // Determine how much space I need.
    // Allocate a buffer of that size + room for null terminator
    // Check for buffer allocation errors
    // Do the copy.
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

  10. #10
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by lehe View Post
    Hi,
    I was wondering how to use strcpy safely so that I can get reported when overwriting happens?
    Or other methods that achieve the same function with security check?
    Also in C++, is there a C++ way to handle it besides using STL string class?
    So you want to take the "ambulance at the bottom of the cliff" approach?
    Why not go so far as to prevent buffer overrun from even happening, by using std::string like you're supposed to?!
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  11. #11
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    ...or at least strncpy...
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  12. #12
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Why exactly is strncpy such a safety feature? OK, it allows you to copy stuff without finding out the length of the source string at first, but then you run the risk that not the entire string is copied and it can be left unterminated if you are not careful. Eventually you'll need to put a lot of work into it to get the same result as with strcpy if your intention is to copy the whole string. It would seem that strncpy has a somewhat different purpose (something like substr )? (I've never felt any need to use strncpy, because if the string manipulation gets this complicated, I'd definitely use std::string)
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by anon
    Why exactly is strncpy such a safety feature? OK, it allows you to copy stuff without finding out the length of the source string at first, but then you run the risk that not the entire string is copied and it can be left unterminated if you are not careful. Eventually you'll need to put a lot of work into it to get the same result as with strcpy if your intention is to copy the whole string.
    You are not being paranoid enough: assume that the contents of the source string cannot be trusted, i.e., it might not be null terminated. strcpy() would then be unable to avoid buffer overrun, whereas strncpy() can.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    You are not being paranoid enough: assume that the contents of the source string cannot be trusted, i.e., it might not be null terminated. strcpy() would then be unable to avoid buffer overrun, whereas strncpy() can.
    Of course that only saves you from overrunning the destination buffer. If the source cannot be trusted (ie not null terminated), then there's still a good chance you will overrun the source buffer.

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by bithub
    If the source cannot be trusted (ie not null terminated), then there's still a good chance you will overrun the source buffer.
    That is why I stated "contents of the source", since it may be a reasonable assumption that the size of the source buffer is known and trusted even when the contents of the source are entirely untrusted.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A Full Program to analyze.
    By sergioms in forum C Programming
    Replies: 2
    Last Post: 12-30-2008, 09:42 AM
  2. Strcpy
    By Godders_2k in forum C Programming
    Replies: 17
    Last Post: 12-12-2007, 12:34 PM
  3. What's up with this strcpy?
    By fanoliv in forum C Programming
    Replies: 7
    Last Post: 06-19-2006, 05:24 PM
  4. Question about strcpy
    By Kevinmun in forum C Programming
    Replies: 4
    Last Post: 11-02-2005, 11:00 PM
  5. strcpy
    By Luigi in forum C++ Programming
    Replies: 17
    Last Post: 02-16-2003, 04:11 PM