那么字面量到底存储在哪里呢?(见下面的示例)
我无法修改字面量,因此它应该是一个const char*,尽管编译器让我使用char*,即使在大多数编译器标志下也没有警告。
而将const char*类型隐式转换为char*类型会给我一个警告,如下所示(在GCC上测试,但在VC++2010上表现类似)。
此外,如果我修改const char的值(通过下面的技巧,在这种情况下GCC最好给我一个警告),它不会出错,甚至可以在GCC上修改和显示它(尽管我猜测它仍然是未定义行为,我想知道为什么它没有对字面量执行相同的操作)。这就是为什么我问字面量存储在哪里,常量通常存储在哪里。
const char* a = "test";
char* b = a; /* warning: initialization discards qualifiers
from pointer target type (on gcc), error on VC++2k10 */
char *c = "test"; // no compile errors
c[0] = 'p'; /* bus error when execution (we are not supposed to
modify const anyway, so why can I and with no errors? And where is the
literal stored for I have a "bus error"?
I have 'access violation writing' on VC++2010 */
const char d = 'a';
*(char*)&d = 'b'; // no warnings (why not?)
printf("%c", d); /* displays 'b' (why doesn't it do the same
behavior as modifying a literal? It displays 'a' on VC++2010 */
VirtualProtect
来解除保护以验证它。 - riv