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?

stackorheap


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.

Advertisements