【发布时间】:2010-11-02 21:11:18
【问题描述】:
似乎strtol() 和strtod() 有效地允许(并强制)你抛弃字符串中的常量:
#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 *,没有任何警告或任何东西。 (实际上,它不允许您将bar 输入为const char *,因此会强制进行不安全的类型更改。)这不是很危险吗?
【问题讨论】:
标签: c constants std c-strings const-char