Click here to Skip to main content
15,668,842 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
As the title referred, I'm trying to figure it out where the pointer variable pointed at.

What I have tried:

#include <stdio.h>
#include <stdlib.h>

void test() {
    char buffer[1024]={0};
    char* mem=(char*)calloc(sizeof(char)*1024,1);
    char* p1=&buffer[0];
    char* p2=mem;

    size_t len_p0=sizeof(buffer);
    size_t len_p1=sizeof(p1);
    size_t len_p2=_msize(p2)/sizeof(char);


    printf("length of local function frame stack:%d\n",len_p0);
    printf("length of local variable itself:%d\n",len_p1);
    printf("length of heap memory:%d\n",len_p2);

void function_about_pointer_at(char* p1,char* p2) {
    //if there is no coding context, is it possible to figure out about p1/p2 , which is pointed at a frame stack memory,
    // which is pointed at a heap memory ?

void main() {
Updated 27-Feb-23 4:31am
Randor 27-Feb-23 23:36pm    
Have a look at how to do this on the Windows operating system:
Yount_0701 28-Feb-23 2:56am    
Impressive. I have a lot to learn.

In your main, declare a local variable, take a pointer to it (p1), and save that address in a global variable.

In the function where you want to check whether a pointer references the stack or the heap, do this again to find p2. If the pointer that you're interested in lies between p1 and p2, it references the stack, else it references the heap.
Share this answer
Technically you can, albeit unreliably. The executable image usually (at least on windows) is always loaded at specific address. If you call GetInstanceHadle() it will return HINSTANCE the starting address of your executable in the computer memory. Usually something like 0x40000000. Normally referred to as HINSTANCE. So anything above this address plus the stack size of all your functions will constitute the "Local Stack". If the memory address lies way beyond this it most definitely be the heap. You would also need to account for any DLLs base HINSTANCE adresses as well such as KERNEL32.DLL, USER32.DLL, CMNCTRL32.DLL etc.
Share this answer
Randor 27-Feb-23 23:39pm    
Short answer: you cannot.
A bit longer answer, you could provide your own wrapper to malloc and the like, see, for instance, c1moore answer here:[^].
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900