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

前端 未结 9 873
广开言路
广开言路 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条回答
  • 2020-12-04 06:49

    strtok() is generally considered to be evil because it stores state information between calls. Don't try running THAT in a multithreaded environment!

    0 讨论(0)
  • 2020-12-04 06:52

    View page 7 (PDF page 9) SAFECode Dev Practices

    Edit: From the page -

    strcpy family
    strncpy family
    strcat family
    scanf family
    sprintf family
    gets family

    0 讨论(0)
  • 2020-12-04 06:53

    strcpy - again!

    Most people agree that strcpy is dangerous, but strncpy is only rarely a useful replacement. It is usually important that you know when you've needed to truncate a string in any case, and for this reason you usually need to examine the length of the source string anwyay. If this is the case, usually memcpy is the better replacement as you know exactly how many characters you want copied.

    e.g. truncation is error:

    n = strlen( src );
    
    if( n >= buflen )
        return ERROR;
    
    memcpy( dst, src, n + 1 );
    

    truncation allowed, but number of characters must be returned so caller knows:

    n = strlen( src );
    
    if( n >= buflen )
        n = buflen - 1;
    
    memcpy( dst, src, n );
    dst[n] = '\0';
    
    return n;
    
    0 讨论(0)
提交回复
热议问题