Home > Software design >  Is it possible to destroy the memory via pointer?
Is it possible to destroy the memory via pointer?

Time:05-15

First I promise that I won't do anything bad with this. I'm just curious.

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char ** argv) {
    int* p;
    while (true) {
        *p = 0;
        p  ;
    }
    
    return 0;
}

CodePudding user response:

Most modern operating systems run in protected mode. What this means is that when you run an application, the operating system is creating a virtual memory space for your application. When a memory allocation command, such as malloc(), tries to allocate memory, the operating system intercepts that and allocates the memory in the virtual memory space that was created when your application first ran, then returns you a pointer to that memory that is in the virtual space. The pointer is a pointer in your application's own virtual space and cannot access memory of other processes or memory of system processes.

In protected mode, there are four privilege levels or rings, numbered from 0 to 3, with ring 0 being the most privileged and 3 being the least. The use of rings allows for system software to restrict tasks from accessing data, call gates or executing privileged instructions.

Now if you were to run your program in an operating system that uses non-protected mode (called real mode), such as DOS or Windows 286, then it would crash your computer. It would not "destroy" the memory, but it would crash it and you would more than likely be forced to power off the computer and power it back on again.

The only exception to this would be if you are writing device drivers. Because device drivers interface directly with hardware, device drivers usually run in ring 0 and are allowed to access system memory areas that would otherwise be inaccessible to regular processes.

CodePudding user response:

Ordinarily, no. If you're running it within a modern OS that is. In such circumstance it will neither have direct access to the computer RAM, or even have unrestricted access to it's own memory space.

A process' memory space is virtual, meaning it doesn't know it's real RAM address, and it doesn't have access to other processes' memory, at least not without using some arcane system APIs. Multiple processes can coexist writing to the same virtual addresses without conflict, and they generally do.

On top of that, there's something called Control-Flow Integrity supported by more modern OS, it basically enforces access restrictions for different memory spaces within the program virtual memory to prevent a number of common attacks. For example, a program can't overwrite it's own code and can't execute code that is in any memory space that hasn't been explicitly flagged with that permission.

  • Related