![]()
What if you call delete operator by using a stack pointer? Like that, while writing frameworks sometimes we expects the pointer that gets passed to the function should point a valid memory block which is allocated on heap itself. So how can we check whether the pointer points to stack or heap in debug version?

![]()
You can use the function – _CrtIsValidHeapPointer(). Its an undocumented CRT function. But it works only in debug version. Well, please check the code snippet below,
#include "malloc.h" ... // Check heap pointer. int* pInteger = new int; BOOL bHeap = _CrtIsValidHeapPointer( pInteger ); // Check stack pointer and you'll get an assertion. char CharArray[100]; bHeap = _CrtIsValidHeapPointer( CharArray );
![]()
Its annoying that its not available in release version. Well, atleast we could make our framework to notify the user while debugging in the debug build. isn’t it?
![]()
Targeted Audience – Beginners.



great work!
BTW, we can check whether a pointer points to stack or heap with the help of Thread Information Block in release version.
bool IsMemoryOnStack( LPVOID pVoid )
{
LPVOID dwStackTop = 0;
LPVOID dwStackLowCurrent = 0;
__asm
{
mov EAX, FS:[4]
mov dwStackTop, eax
mov EAX, FS:[8]
mov dwStackLowCurrent, eax
}
if( pVoid = dwStackLowCurrent )
{
// The memory lie between the stack top and stack commited.
return true;
}
// Pointer dosen’t point to the stack
return false;
}
void main()
{
int OnStack;
bool bOnStack = IsMemoryOnStack( &OnStack );// Returns true
int *pOnHeap = new int;
bOnStack = IsMemoryOnStack( pOnHeap );// Returns false
}
hope this be useful!
Wow! Thats Superb! Thanks a lot leochou, for sharing this tip. May be I’ll update this to the tip with your name.
Well, Thanks once again and keep watching.
Regards,
Jijo.