Reputation: 551
Will this program delete all the contents of RAM? I dared not to run it on my PC. And there was no use of doing it on online compilers.
#include <iostream>
using namespace std;
int main() {
int a = 10;
int *p;
p = &a;
for(int i = 0;i>=0;i++){
*(p+i) = 0;
}
return 0;
}
Upvotes: 0
Views: 117
Reputation: 75545
In general, a program can only touch memory inside its virtual address space, so no, this program will not "delete all of RAM" even if that were possible for some definition of "delete".
int
wraps around to the negatives. The program should at that point crash because you have overwritten the return address for the function main
.p + 1 == &i
under my system. Thus, the loop perpetuates indefinitely, because i
gets reset to 0
after every iteration of the body of the loop, and increments to 1
at the end of the loop.-g
, and inside gdb
, I interrupted the program with Control-C
and printed p + i
and &i
and observed that they were the same.Note that my observation may be specific to my system and is definitely specific to my compiler options.
Upvotes: 2
Reputation: 21241
On modern machines / OS's, each process has it's own virtual address space. One job of the OS is to map sections (pages) of this address space to real memory, and to swap out unused areas to disk. This is what allows multiple programs with memory demands far greater than the physical RAM to all run at once. It's also what causes "disk thrashing" if you don't have enough RAM, as the OS is constantly having to read and write pages of memory to the swap file.
This also protects the rest of the system from badly written programs. One process cannot affect memory used by another. Only the bad one will crash.
Additionally, areas of memory within the virtual address space can have access modifiers. For instance, Windows will use some of the memory to store the code that is being run. You don't want to be accidentally writing over this code, so it gets marked as readonly. This is why you will get an access violation if you attempt to write to address 0, even though address 0 is in your virtual address space.
Upvotes: 0