RisenShadow
RisenShadow

Reputation: 57

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;
    }

Upvotes: 1

Views: 185

Answers (2)

Tumbleweed53
Tumbleweed53

Reputation: 1551

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.

Upvotes: 3

likle
likle

Reputation: 1797

I guess it depends where you run it, but usually there is memory protection, which means you can't just write outside of the processes memory.

Upvotes: 3

Related Questions