Thread: Any point to strnlen?

  1. #1
    Registered User
    Join Date
    Nov 2013
    Posts
    107

    Any point to strnlen?

    From MSDN

    'strnlen is not a replacement for strlen; strnlen is intended to be used only to calculate the size of incoming untrusted data in a buffer of known size—for example, a network packet. strnlen calculates the length but doesn't walk past the end of the buffer if the string is unterminated.'


    I came upon strnlen in some source, never seen it before, seems that it's used in Unix and MS have their own version though not standard C/C++.


    So it checks a string against a buffer of known size and if > buffer returns string up to max buffer size.
    So don't see how this is needed, terminated or not strlen is less work and does same thing?




    Code:
    size_t buffer = 1000;
    
    
    if (strlen(str) > buffer){
       return -1
    }
    as even if you used strnlen you would still have to at least say


    Code:
    size_t buffer = 1000;
    
    
    unsigned int i_str = strnlen(str, buffer);
    
    
    if i_str == buffer{
       return -1
    }

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    strlen() keeps walking over memory until it finds a character with value zero.

    If it falls off the end of the array, it has undefined behaviour. In your first version, for example, strlen() may never return.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    More practically, strlen() may cause an access violation when reading beyond allocated space, thereby crashing your program.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 04-27-2011, 04:34 AM
  2. strnlen, implicit declaration?
    By AngryStyro in forum C Programming
    Replies: 17
    Last Post: 04-19-2008, 04:40 AM
  3. Point to Point Protocol and Bluetooth DUN
    By PSLoh in forum Networking/Device Communication
    Replies: 2
    Last Post: 03-03-2008, 09:44 AM
  4. fixed point / floating point
    By confuted in forum Game Programming
    Replies: 4
    Last Post: 08-13-2002, 01:25 PM
  5. Floating point faster than fixed-point
    By VirtualAce in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 11-08-2001, 11:34 PM