understanding the dangers of sprintf(…)

前端 未结 8 1439

OWASP says:

\"C library functions such as strcpy (), strcat (), sprintf () and vsprintf () operate on null terminated strings and perform no bou

8条回答
  •  既然无缘
    2020-12-01 05:06

    Both of your assertions are correct.

    There's an additional problem not mentioned. There is no type checking on the parameters. If you mismatch the format string and the parameters, undefined and undesirable behavior could result. For example:

    char buf[1024] = {0};
    float f = 42.0f;
    sprintf(buf, "%s", f);  // `f` isn't a string.  the sun may explode here
    

    This can be particularly nasty to debug.

    All of the above lead many C++ developers to the conclusion that you should never use sprintf and its brethren. Indeed, there are facilities you can use to avoid all of the above problems. One, streams, is built right in to the language:

    #include 
    #include 
    
    // ...
    
    float f = 42.0f;
    
    stringstream ss;
    ss << f;
    string s = ss.str();
    

    ...and another popular choice for those who, like me, still prefer to use sprintf comes from the boost Format libraries:

    #include 
    #include 
    
    // ...
    
    float f = 42.0f;
    string s = (boost::format("%1%") %f).str();
    

    Should you adopt the "never use sprintf" mantra? Decide for yourself. There's usually a best tool for the job and depending on what you're doing, sprintf just might be it.

提交回复
热议问题