-2

I wrote the following function:

template <typename T> void SetPointer(DWORD64 base, vector<DWORD>Offsets, T value){
base = *reinterpret_cast<DWORD64*>(base);
for (int i = 0; i < Offsets.size() - 1; i++){
    base = *reinterpret_cast<DWORD64*>(base + Offsets[i]);
}
*reinterpret_cast<T*>(base + Offsets[Offsets.size() - 1]) = value;
}

It works perfectly, except that I'd like to have checks to make sure the address is valid and that it won't cause a crash, but I haven't found any way that works well to do that. What would be the best way to acheive this?

Edit: This did the trick for what I need:

template <typename T> void SetPointer(DWORD64 base, vector<DWORD>Offsets, T value){
if (base == 0) return;
base = *reinterpret_cast<DWORD64*>(base);
for (int i = 0; i < Offsets.size() - 1; i++){
    base = *reinterpret_cast<DWORD64*>(base + Offsets[i]);
    if (base == Offsets[i] || base == 0) return;
}
*reinterpret_cast<T*>(base + Offsets[Offsets.size() - 1]) = value;
}
Talococh
  • 17
  • 6
  • 3
    It's not possible. – user253751 Jun 13 '16 at 21:00
  • You can't, there is no way to know (aside nullptr/0) – Davidbrcz Jun 13 '16 at 21:01
  • But if you're curious you can play with signals, especially handling `SIGSEGV`. But that's bad practice as standard doesn't say anything about dereferencing invalid pointer, thus it's **undefined behaviour**. But it *just Works*™. – PcAF Jun 13 '16 at 21:06
  • *I'd like to have checks to make sure the address is valid* -- Why? Fix the bug in your code that provided the bad pointer. – PaulMcKenzie Jun 13 '16 at 21:09
  • Can't fix it, the issue is that the pointer is valid when the game is loaded and invalid when the game is on loading screen etc. – Talococh Jun 13 '16 at 21:14
  • So don't point to something that can be invalidated. This is no different than when a programmer points to a `std::vector's` internal buffer, and something mutates the vector, invalidating the pointer that was pointing to that location. – PaulMcKenzie Jun 13 '16 at 21:20

1 Answers1

1

tl;dr: It's impossible.

Long version: Windows has functions called IsBadXxxPtr here is what a renowned Microsoft programmer has to say about them and their functionality:

IsBadXxxPtr should really be called CrashProgramRandomly

RedX
  • 14,749
  • 1
  • 53
  • 76