“获取功能...可能不安全”。 -真的吗? [英] "getenv... function ... may be unsafe" - really?
问题描述
我正在使用MSVC编译一些使用标准库函数的C代码,例如 getenv()
, sprintf
和其他设置为 / W3
的警告。 MSVC告诉我:
I'm using MSVC to compile some C code which uses standard-library functions, such as getenv()
, sprintf
and others, with /W3
set for warnings. I'm told by MSVC that:
‘getenv’:此函数或变量可能不安全。考虑改用_dupenv_s。要禁用弃用,请使用_CRT_SECURE_NO_WARNINGS
'getenv': This function or variable may be unsafe. Consider using _dupenv_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS
问题:
- 从理论上讲,与在其他平台上使用相比,为什么这是不安全的?
- 实际上在Windows上是否不安全?
- 假设我不是在编写面向安全性的代码-我应该禁用此警告还是应该真正为一系列标准库函数起别名?
推荐答案
getenv()
可能是不安全的,因为对同一函数的后续调用可能会使先前返回的指针无效。结果,使用诸如
getenv()
is potentially unsafe in that subsequent calls to that same function may invalidate earlier returned pointers. As a result, usage such as
char *a = getenv("A");
char *b = getenv("B");
/* do stuff with both a and b */
可能会中断,因为没有保证 a
仍然可以使用。
may break, because there's no guarantee a
is still usable at that point.
getenv_s()
-自C11起在C标准库中提供-避免这种情况立即将值复制到调用方提供的缓冲区中,在此缓冲区中,调用方可以完全控制缓冲区的生存期。 dupenv_s()
通过使调用方负责管理分配的缓冲区的生存期来避免这种情况。
getenv_s()
- available in the C standard library since C11 - avoids this by immediately copying the value into a caller-supplied buffer, where the caller has full control over the buffer's lifetime. dupenv_s()
avoids this by making the caller responsible for managing the lifetime of the allocated buffer.
但是, getenv_s
的签名有些争议,甚至有时甚至可以从C标准中将其删除 ……请参见此报告。
However, the signature for getenv_s
is somewhat controvertial, and the function may even be removed from the C standard at some point... see this report.
这篇关于“获取功能...可能不安全”。 -真的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!