关键词搜索

源码搜索 ×
×

为什么snprintf比sprintf更安全?(另外,请注意, Windows和Linux中的snprintf函数有区别)

发布2014-04-12浏览22395次

详情内容

       在前面的博文中,我们深入分析了strcpy和strncpy, 并指出,谁要再用strcpy, 谁就是流氓, 下面,我们来看看与之类似的sprintf和snprintf.  实际上, 在VC++6.0中,用的是_snprintf, 为了方便起见,叙述的时候,我还是用snprintf.

 

       看下面测程序(设data为某一情况下产生的数据):

 

  1. #include <iostream>
  2. #include <cstring>
  3. #define snprintf _snprintf
  4. using namespace std;
  5. int main()
  6. {
  7. char str[10] = {0};
  8. char *data = "ab";
  9. sprintf(str, "debug : %s", data);
  10. cout << str << endl;
  11. return 0;
  12. }

 

      我运行上述程序, 非常侥幸, 没有错误。 但是, 我说了,data是某种情况下产生的数据,所以长度有可能不一定,要是万一data在极端情况下比较长,那会怎么样呢?直接上代码:

 

  1. #include <iostream>
  2. #include <cstring>
  3. #define snprintf _snprintf
  4. using namespace std;
  5. int main()
  6. {
  7. char str[10] = {0};
  8. char *data = "abcdefg";
  9. sprintf(str, "debug : %s", data);
  10. cout << str << endl;
  11. return 0;
  12. }

      我运行了一下程序,发现程序可以编译过,但是在运行期间崩溃。要是在大系统中,用户肯定会找你麻烦,你的产品何谈竞争力?

 

 

      可以做如下修改:

 

  1. #include <iostream>
  2. #include <cstring>
  3. #define snprintf _snprintf
  4. using namespace std;
  5. int main()
  6. {
  7. char str[10] = {0};
  8. char *data = "abcdefg";
  9. snprintf(str, sizeof(str) - 1, "debug : %s", data);
  10. cout << str << endl;
  11. return 0;
  12. }

     这样就安全了,和strncpy非常类似。

 

 

     另外,需要特别注意的是: Windows和Linux中的snprintf函数有区别, 在linux代码中,经常见到snprintf(str, sizeof(str), "...")这样的用法, 为什么这里不是sizof(str) - 1呢?

我们看看Windows下这么用会怎样:

 

  1. #include <iostream>
  2. #include <cstring>
  3. #define snprintf _snprintf
  4. using namespace std;
  5. int main()
  6. {
  7. char str[10] = {0};
  8. char *data = "abcdefgddddddddddddddddddddd";
  9. snprintf(str, sizeof(str), "debug : %s", data);
  10. cout << str << endl;
  11. return 0;
  12. }

     我运行的时候,程序没有崩溃,算是万幸。 但结果乱码。看来,没有自动在str最后加'\0',  在linux中, 就安全了, 会自动补哈, 所以永远不会越界。

 


     总结一下: 

     1. Linux中, 对于snprintf, 用sizeof(str),  最后会自动加'\0', 比strncpy更安全省事。

     2. Windows中, 就把snprintf和strncpy理解为类似的, 要用sizeof(str) - 1, 需要注意最后的'\0', 当然啦,你可以在每次用strncpy之前,利用memset将串清零, 这样比较好。VC++6.0中的_snprintf(snprintf)并没有按要求实现, 晕。

      
 

 

相关技术文章

最新源码

下载排行榜

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载