This valid check checked in windows only (VS),here is the function:
#pragma once
//ptrvalid.h
__inline bool isValid(void* ptr) {
if (((uint)ptr)&7==7)
return false;
char _prefix;
__try {
_prefix=*(((char*)ptr)-1);
} __except (true) {
return false;
}
switch (_prefix) {
case 0: //Running release mode with debugger
case -128: //Running release mode without debugger
case -2: //Running debug mode with debugger
case -35: //Running debug mode without debugger
return false;
break;
}
return true;
}
Usage:
#include <stdio.h>
#include "ptrvalid.h"
void PrintValid(void* ptr) {
if (isValid(ptr))
printf("%d is valid.\n",ptr);
else
printf("%d is not valid.\n",ptr);
}
int main() {
int* my_array=(int*)malloc(4);
PrintValid(my_array);
PrintValid((void*)99);
free(my_array);
PrintValid(my_array);
my_array=new int[4];
PrintValid(my_array);
delete my_array;
PrintValid(my_array);
getchar();
}
Output:
764776 is valid.
99 is not valid.
764776 is not valid.
774648 is valid.
774648 is not valid.
Function's explanation: (What it does)
The functions check before the real checking ,if the address is valid\start point to memory.
After that he checks if this process can reach this memory's prefix (If caught exception if can't) and the last checking is checking what the prefix of this memory if deleted at any mode. (Debugging\Without Debug Mode\Release Mode)
If the function passed all of those checks ,it returns true.