【发布时间】:2020-11-02 17:10:10
【问题描述】:
上次我问我如何绕过编译器不覆盖const 内存的承诺,在程序中生成segmentation 错误。用户Marco Bonelli 描述了以下方式,效果很好。
const static int global = 123;
int main(void) {
int *ptr = (int *)&global;
*ptr = 456;
// or, equivalent
const int *ptr2 = &global;
*(int *)ptr2 = 456;
}
无论哪种方式,我都能产生分段错误。
-
int *ptr = (int *)&global; *ptr = 456; -
const int *ptr2 = &global; *(int *)ptr2 = 456;
现在我的问题是是什么阻止了指针写入global const 内存块而不是local const 内存块。例如,在下面的代码中,我可以毫无问题地写入const 内存块。
#include <stdio.h>
int main(void) {
const int local = 123;
int *ptr = (int *)&local;
*ptr = 456;
// how come this be possible?
printf("%d\n", local); // -> 456
// or, equivalent
const int *ptr2 = &local;
*(int *)ptr2 = 512;
// how come this be possible?
printf("%d\n", local); // -> 512
}
我很想知道这是怎么发生的。请赐教。
如果重要的话,我正在使用gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0。
【问题讨论】:
-
当你的程序终止时,这个“块”会发生什么——与编译器无关,也与编译器无关。这两个程序没有任何共同点,第一个程序的运行不应以任何方式影响第二个程序。该内存由操作系统回收。对于覆盖
const的问题 - 通常这是一个坏主意。它是const是有原因的,不应更改。 -
你能解释一下你想要达到的目标吗?
-
试图存储到声明为
const的内存中会导致未定义的行为。 -
您在这里问了几个不同的、不相关的问题。要点是一个进程中的物理内存完全独立于任何其他进程中的物理内存(假设您没有执行明确的mmap())。您可能想详细了解物理和逻辑内存空间之间的区别:en.wikipedia.org/wiki/Virtual_memory。
-
你想做什么?破解什么?在其脚下修改其他程序数据?还有什么?