C ++字符串和流缓冲区溢出安全吗? [英] Are C++ strings and streams buffer overflow safe?

查看:78
本文介绍了C ++字符串和流缓冲区溢出安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用std :: cin,std :: cout和std :: string,有人会利用缓冲区溢出吗?

If I use std::cin, std::cout and std::string, is there any possibility that someone will exploit the buffer overflow?

之所以这样问,是因为我仍然看到很多人仍然使用以N结尾的字符串而不是C ++中的标准容器.

I ask this because I still see a lot of people that still use null-terminated strings instead of standard containers in C++.

推荐答案

这要视情况而定.当然,当您使用C样式的代码/API时,没有区别.

It depends. Of course, when you use C-style code/API's, there is no difference.

但是使用STL或C ++习惯用法并不能保证您的安全.

But using STL or C++ idioms doesn't guarantee that you're safe.

C ++始终为您提供选择.对比这两个几乎相同的双胞胎:

C++ gives you the choice, always. Contrast these two near-identical twins:

int n;
std::cin >> n;
std::string s(n, '*'); // create a data store of given size

std::vector<char> v(1000);
std::copy(s.begin(), s.end(), v.begin()); // NOT safe if n > 1000

安全变体:

int n;
std::cin >> n;
if (n > MAX_LIMIT) 
    throw std::runtime_error("input too large");
std::string s(std::min(0, n), '*'); // note input sanitation

std::vector<char> v;
v.reserve(1000);
std::copy(s.begin(), s.end(), std::back_inserter(v)); // safe

这篇关于C ++字符串和流缓冲区溢出安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆