How to check whether the Pointer is allocated in Stack or Heap in Debug?

14 12 2008

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.




2 responses

15 12 2008

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;
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!

15 12 2008

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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: