【发布时间】:2011-03-05 17:45:58
【问题描述】:
内存中的文字到底在哪里? (见下面的例子)
我不能修改文字,所以它应该是 const char*,虽然编译器允许我使用 char*,但即使使用大多数编译器标志,我也没有警告。
而将 const char* 类型隐式转换为 char* 类型会给我一个警告,见下文(在 GCC 上测试,但在 VC++2010 上表现类似)。
另外,如果我修改 const char 的值(在下面使用 GCC 最好给我警告的技巧),它不会出错,我什至可以修改并在 GCC 上显示它(即使我猜到了仍然是一个未定义的行为,我想知道为什么它没有对文字做同样的事情)。这就是为什么我要问这些文字存储在哪里,以及更常见的 const 应该存储在哪里?
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 */
【问题讨论】:
-
有人可以消除标题的歧义以引用“字符串文字”
-
至于第二个示例,至少在 Windows 上,文字位于写保护页面中,很可能与实际说明一起。您可以通过
VirtualProtect解除保护验证。