Yes, you can check if a pointer is pointing to an allocated memory of certain size.
But no, you can't check if it points to the "correct" object. But since this wasn't your question, I will assume you only care if dereferencing a pointer would cause a crash in your program.
bool wouldDereferencingCauseCrash(int* ptr); //checks if ptr points to sizeof(int)
//allocated on heap bytes
int* a = new(int);
int* b = a;
wouldDereferencingCauseCrash(b); //returns false - b points to memory alocated for a
free(a);
wouldDereferencingCauseCrash(b); //returns true - b points to freed memory chunk
int* c = new(int);
wouldDereferencingCauseCrash(b); //returns ???? - b points to either freed memory
// or memory allocated for c
Now how would we implement this mysterious function "wouldDereferencingCauseCrash"?
First, the basics. Let's assume you're using GCC compiler, and new() is actually just a malloc() in disguise (which is usually the case).
Heap is one contiguous block of memory. Malloc() returns a chunk of memory which for our purposes looks like this:
//this is a simplification but you can deduce all these parameters from the original
//struct contained in malloc.c
struct memory_chunk{
void* ptrToPreviousChunk; //we can deduce pointer to prev. allocated memory_chunk
void* ptrToNextChunk; //we can deduce pointer to next allocated memory_chunk
void* ptrToChunk; //this is what malloc() returns - usable memory.
int sizeOfChunk; //we can deduce if this holds sizeof(int) bytes
};
Now if we just iteratore through all the allocated chunks and find our pointer - we know it points to an allocated memory. If sizeOfChunk is also sizeof(int) - we know it holds an integer. Voila, dereferencing this pointer won't cause a crash. Great! But just to be safe, don't try to write to this memory, copy it first :).
Now the hard stuff:
1/ depending on your compiler, malloc() might work differently,
2/ malloc() sometimes doesn't allocate memory chunks on the heap, sometimes it maps them using mmap() (but usually only if they are very very big),
3/ new() might not be based on malloc() (not likely),
4/ I simplified this quite a bit, read sources if you're intrested in implementing any of this. I recommend using unique_ptr instead or tracking the allocations/deallocations in some kind of a map.
Good luck! :) I hope I don't see this nonsense anywhere near me though :)
Sources:
https://sourceware.org/glibc/wiki/MallocInternals
https://reversea.me/index.php/digging-into-malloc/