Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

Pointer writing to memory loop in c++

I am trying to understand pointers and curious about some things. For example If I run this or this kind of program can I change the values of some hexadecimals that is not used by this program? Does OS do something to defend itself?

    int num1 = 1;
    int num2 = 2;
    int *var1,var2;

    var2 = num1 + num2;
    var1 = &var2;

    for (int counter1 = 0; counter1 < 100000; counter1++) {
        
        *(var1 + counter1) = 0;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

On most modern OS's, your process's memory is isolated from that of every other process and the OS itself. So while your code can trash your own process's memory and do a lot of damage, you can't harm other processes in this way, nor can you harm the OS.

Brief historical note: this was not always the case, and it's still not the case in some OSes (typically for embedded devices, specialized electronics, etc). In those situations, you absolutely can trash the memory of the whole system and of other processes. That's one reason that versions of Windows before Windows XP (ME, 95, 3.1, etc) were so unstable. One rogue process could torpedo the whole system.

Code that is privileged can usually read or write the memory of other processes, even today.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...