是什么使C标准库功能变得危险,替代品是什么? [英] What makes a C standard library function dangerous, and what is the alternative?

查看:103
本文介绍了是什么使C标准库功能变得危险,替代品是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在学习C时,我经常会遇到一些资源,这些资源建议不要使用某些功能(例如gets()),因为它们很难或不可能安全地使用.

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 impossible to use safely.

如果C标准库包含许多这些永不使用"的功能,则似乎有必要学习它们的列表,使它们变得不安全的原因以及怎么做.

If the C standard library contains a number of these "never-use" functions, it would seem necessary to learn a list of them, what makes them unsafe, and what to do instead.

到目前为止,我已经了解了以下功能:

So far, I've learned that functions which:

  • 无法防止覆盖内存
  • 不能保证以空值结尾的字符串
  • 维持通话之间的内部状态

通常被认为是不安全的使用.有列出这些行为的功能列表吗?还有其他类型的功能无法安全使用吗?

are commonly regarded as being unsafe to use. Is there a list of functions which exhibit these behaviours? Are there other types of functions which are impossible to use safely?

推荐答案

在过去,大多数字符串函数都没有边界检查.当然,他们不能只是删除旧功能,也不能修改其签名以包括上限,这会破坏兼容性.现在,对于这些功能中的几乎每个功能,都有一个替代的"n"版本.例如:

In the old days, most of the string functions had no bounds checking. Of course they couldn't just delete the old functions, or modify their signatures to include an upper bound, that would break compatibility. Now, for almost every one of those functions, there is an alternative "n" version. For example:

strcpy -> strncpy
strlen -> strnlen
strcmp -> strncmp
strcat -> strncat
strdup -> strndup
sprintf -> snprintf
wcscpy -> wcsncpy
wcslen -> wcsnlen

还有更多

另请参阅 https://github.com/leafsr/gcc-poison 项目,以创建一个头文件,如果使用不安全的函数,该文件将导致gcc报告错误.

See also https://github.com/leafsr/gcc-poison which is a project to create a header file that causes gcc to report an error if you use an unsafe function.

这篇关于是什么使C标准库功能变得危险,替代品是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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