开发者

Windows: pointer unicity

I had a need of a quick unique ID in one of my classes to differenciate one process from another. I decided to use the address of the instance to do so. I ended up with something like this (quintptr is a Qt defined ty开发者_Python百科pe of integer to store addresses with the correct size, according to the platform):

Foo::Foo()
: _id(reinterpret_cast<quintptr>(this))
{
 ...
}

The idea is to compare the output of two different processes of the same exe. On Vista (my dev machine) there's no problem. But on XP, the value of _id is the same (!) in the two processes.

Can anyone explain why is that? and if it's a good idea to use pointers like that (I thought so, I'm not so sure anymore)?

Thanks.


Every process gets its own address space. On XP, they're all the same. Therefore it's very common to see what you saw: two objects that have the same address, but in two different address spaces.

It turns out that this contributes to security risks. Attackers were able to guess where vulnerable objects would be in memory, and exploit those. Vista randomizes address spaces (ASLR) which means that two processes are far more likely to put the same object at different addresses.

For your case, using pointers like that is not a smart idea. Just use the process ID


The reason is each process has its own address space and if two processes do the same they just use the same virtual addresses - maybe even heap allocations will be done at same virtual addresses.

You could call GetCurrentProcessId() once and store the result somewhere so that further retrieval is very fast. The process id persists and is unique for the lifetime of the process.


Each process gets its own address space. Unless something like ASLR kicks in, the memory layouts of two processes stemming from the same executable are likely to be very similar, if not identical.

So your idea is not a good one. Using the process ID sounds like a saner approach here, but keep in mind that those can be recycled too.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜