开发者

C++: Can I get out of the bounds of my app's memory with a pointer?

开发者 https://www.devze.com 2023-01-02 13:12 出处:网络
If I have some stupid code like this: int nBlah = 123; int* pnBlah = &nBlah; pnBlah += 80000; *pnBlah = 65;

If I have some stupid code like this:

int nBlah = 123;
int* pnBlah = &nBlah;
pnBlah += 80000;
*pnBlah = 65;

Can I change another app's memory?

You have explained me this is evil, I know开发者_运维技巧. But I was just interested.

And this isn't something to simply try. I don't know what would happen.

Thanks


In C++ terms, this is undefined behavior. What will actually happen depends on many factors, but most importantly it depends on the operating system (OS) you are using. On modern memory-managed OS's, your application will be terminated with a "segmentation fault" (the actual term is OS-dependent) for attempting to access memory outside of your process address space. Some OS's however don't have this protection, and you can willy-nilly poke and destroy things that belong to other programs. This is also usually the case if your code is inside kernel space, e.g. in a device driver.


Nope, it's not that simple. :)

Modern operating systems use virtual memory.

Every process is provided with a full virtual address space.

Every process is given its own "view" of all addresses (from 0x00000000 to 0xffffffff on a 32-bit system). Processes A and B can both write to the same address, without affecting each others, because they're not accessing physical memory addresses, but virtual addresses. When a process tries to access a virtual address, the OS translates that into some other physical address to avoid collisions.

Essentially, the OS keeps track of a table of allocate memory pages for every process. It tracks which address ranges have been allocated to a process, and which physical addresses they're mapped to. If a process tries to access an address not allocated to it, you get an access violation/segmentation fault. And if you try to access an address that is allocated to your process, you get your own data. So there is no way to read other processes data just by typing in the "wrong" address.


Under modern operating systems you don't get access to the real memory, but rather a virtual memory space of 4gb (under 32bit). Bottom 2gb for you to use, and top 2gb reserved for the operating system.

This does not reflect to actual memory bytes in the RAM.

Every app get's the same virtual address space, so there is no straight forward way of accessing another process's memory space.


I think this would raise 0x00000005, access violation on windows


Modern operating systems have various means of protecting against these kinds of exploits that write into the memory space of other programs. Your code wouldn't work either way, I don't think.

For more information, read up on Buffer Overflow exploits and how they gave Microsoft hell prior to the release of Windows XP SP2.

0

精彩评论

暂无评论...
验证码 换一张
取 消