Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Can I access restricted memory space by pointers

So when I learnt about pointers, I got some crazy idea: If I print a pointer, it gives an address in the memory, and if so, what part of the computer's memory is actually read? For example

#include <iostream>
using namespace std;
main()
{
   int a=1;
   int* ptr=&a;
   int i=0;
   while(1)
   {
      cout<<(ptr+i)<<""<<*(ptr+i)<<"
";
      i++;
   }
}

When I run this program (considering no errors) it gives me addresses from &a ++. So it loops through addresses in memory, and displays the information stored there. So my question is, which part of the memory is being read? And is it possible for me to access every single memory location (the value that is stored in each)? Can I delete (this sounds stupid as hell) files on my computer by sth like this

ptr=nullptr;
while(1)
{
   *(ptr+i)=0;
   i++;
}

I don't know whether my syntax is correct, though you get the idea. I don't dare run this on my computer...

question from:https://stackoverflow.com/questions/65849627/can-i-access-restricted-memory-space-by-pointers

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

1 Reply

0 votes
by (71.8m points)

No, if you could do this then the "restriction" would be useless.

In the past - think: the MS-DOS and Windows 3.1 days - you could do this. And it would overwrite memory belonging to other programs, and probably crash the computer.

Modern operating systems use a technique called virtual memory, where the operating system controls your addresses! Whenever you access a pointer 0x12345678, the CPU looks in the page table for information about page 0x12345.

If that's a page belonging to your program, it will change the page address to what the page table says - so now it's 0xabcde678 - and get the data from that RAM chip. This allows the operating system to move pages around without your program noticing. One moment 0x12345678 means 0xabcde678, and the next moment it means 0x54321678, and you couldn't tell the difference.

If it's not a page belonging to your program, there will be no new address in the page table. In this case, the CPU raises a page fault exception - it calls a specific function in the operating system which deals with page faults. This function will see that there is no good reason for the page fault (because there are some good reasons). It ends your program and pops up a message box saying "This program has encountered a problem and needs to close".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...