是否安全使用malloc? [英] Is it secure to use malloc?
问题描述
有人告诉我说,使用malloc分配是不安全了,我不是一个C / C ++大师,但我做了一些东西用malloc和C / C ++。有谁知道什么风险,我把?
引述他:
[..]不过说实在的C / C的薄弱点++它是安全的,而阿喀琉斯之踵确实是malloc和指针的滥用。 C / C ++是一个众所周知的不安全的语言。 [..]会有什么我不建议继续与C ++编程几个应用程序。
块引用>解决方案
...] C / C ++它是一个众所周知的不安全的语言。 [...]
块引用>其实,这是错误的。 的其实,C / C ++根本不存在。的有 C 的,然后还有的 C ++ 的。他们分享一些(或者,如果你想,一个不少)语法,但他们确实的非常不同的语言的。
他们大大不同,有一件事是他们的管理动态存储方式。的C方式确实使用
的malloc()
/免费()
,如果你需要动态内存还有否则你很少可以做,但使用它们(或的malloc几个兄弟姐妹()
)。结果
C ++的办法是不要的 (手动)的的处理动态资源的(它的内存只有一个)的所有的。资源管理标准库交给几个精心实施,-tested类,preferably,然后自动完成。例如,而不是手动处理零结尾的字符缓冲区,有的std :: string的
,而不是手动处理动态分配数组,有STD :矢量
,而不是与打开的文件手动处理,还有的的std :: fstream的
家庭流等。Somebody told me that allocating with malloc is not secure anymore, I'm not a C/C++ guru but I've made some stuff with malloc and C/C++. Does anyone know about what risks I'm into?
Quoting him:
[..] But indeed the weak point of C/C++ it is the security, and the Achilles' heel is indeed malloc and the abuse of pointers. C/C++ it is a well known insecure language. [..] There would be few apps in what I would not recommend to continue programming with C++."
解决方案[...] C/C++ it is a well known insecure language. [...]
Actually, that's wrong. Actually, "C/C++" doesn't even exist. There's C, and there's C++. They share some (or, if you want, a lot of) syntax, but they are indeed very different languages.
One thing they differ in vastly is their way to manage dynamic memory. The C way is indeed using
malloc()
/free()
and if you need dynamic memory there's very little else you can do but use them (or a few siblings ofmalloc()
).
The C++ way is to not to (manually) deal with dynamic resources (of which memory is but one) at all. Resource management is handed to a few well-implemented and -tested classes, preferably from the standard library, and then done automatically. For example, instead of manually dealing with zero-terminated character buffers, there'sstd::string
, instead of manually dealing with dynamically allocated arrays, therestd:vector
, instead of manually dealing with open files, there's thestd::fstream
family of streams etc.这篇关于是否安全使用malloc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!