正在与strtol,不安全的strtod? [英] Are strtol, strtod unsafe?
问题描述
似乎与strtol()
和关于strtod()
有效地允许(和力),你要抛弃常量性在一个字符串:
It seems that strtol()
and strtod()
effectively allow (and force) you to cast away constness in a string:
#include <stdlib.h>
#include <stdio.h>
int main() {
const char *foo = "Hello, world!";
char *bar;
strtol(foo, &bar, 10); // or strtod(foo, &bar);
printf("%d\n", foo == bar); // prints "1"! they're equal
*bar = 'X'; // segmentation fault
return 0;
}
在上面,我没有进行任何蒙上自己。然而,与strtol()
基本上投我为const char *
到的char *
对我来说,没有任何警告或任何东西。 (事实上,它不会让你键入栏
为为const char *
等强制不安全在类型更改。)是不是很危险?
Above, I did not perform any casts myself. However, strtol()
basically cast my const char *
into a char *
for me, without any warnings or anything. (In fact, it wouldn't allow you to type bar
as a const char *
, and so forces the unsafe change in type.) Isn't that really dangerous?
推荐答案
我猜想,因为选择是雪上加霜。假设原型改为添加常量
:
I would guess that because the alternative was worse. Suppose the prototype were changed to add const
:
long int strtol(const char *nptr, const char **endptr, int base);
现在,假设我们要分析非常量字符串:
Now, suppose we want to parse a non-constant string:
char str[] = "12345xyz"; // non-const
char *endptr;
lont result = strtol(str, &endptr, 10);
*endptr = '_';
printf("%s\n", str); // expected output: 12345_yz
但是,当我们试图编译这个code会发生什么?编译器错误!这是相当不直观,但你不能在的char **
隐式转换为为const char **
。请参阅 C ++ FAQ精简版获取的详细说明为什么。从技术上谈论C ++的存在,但参数也同样适用于C.在C / C ++,你只允许隐式地转换指针的键入的到指针常量
的键入的最高级别:您可以执行转换是从的char **
到 char * const的*
,或等价的指针(指向字符
)到指针(常量
指针字符
)。
But what happens when we try to compile this code? A compiler error! It's rather non-intuitive, but you can't implicitly convert a char **
to a const char **
. See the C++ FAQ Lite for a detailed explanation of why. It's technically talking about C++ there, but the arguments are equally valid for C. In C/C++, you're only allowed to implicitly convert from "pointer to type" to "pointer to const
type" at the highest level: the conversion you can perform is from char **
to char * const *
, or equivalently from "pointer to (pointer to char
)" to "pointer to (const
pointer to char
)".
由于我猜想,分析非常量字符串比解析字符串常量更有可能,我会去上推测常量
-incorrectness的可能性不大情况是preferable以使常见的情况编译错误。
Since I would guess that parsing a non-constant string is far more likely than parsing a constant string, I would go on to postulate that const
-incorrectness for the unlikely case is preferable to making the common case a compiler error.
这篇关于正在与strtol,不安全的strtod?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!