Click here to Skip to main content
15,880,854 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:

C++
#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);

    function_about_pointer_at(p1,p2);

    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() {
    test();
}
Posted
Updated 27-Feb-23 4:31am
v2
Comments
[no name] 27-Feb-23 23:36pm    
Have a look at how to do this on the Windows operating system:
https://www.codeproject.com/Messages/2467319/Re-Determine-Location-of-a-Variable
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
 
Comments
[no name] 27-Feb-23 23:39pm    
ASLR
https://en.wikipedia.org/wiki/Address_space_layout_randomization
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: https://stackoverflow.com/questions/1576300/checking-if-a-pointer-is-allocated-memory-or-not[^].
 
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