0

For C programmers.

How can I know if a pointer char *, for example, was initialized by using malloc or realloc? I mean in kind of that function:

char* func(char** x){
    /* need some reallocating of *x but 
     * *x can be a pointer to const string
     */
}
Pycz
  • 366
  • 3
  • 12
  • possible duplicate of [How to determine if returned pointer is on the stack or heap](http://stackoverflow.com/questions/16709946/how-to-determine-if-returned-pointer-is-on-the-stack-or-heap) – Sergey Kalinichenko Sep 19 '13 at 17:47
  • @dasblinkenlight It must be true in most cases. – Pycz Sep 19 '13 at 18:02
  • realloc can very well use malloc internally. Why do you want to know? – resultsway Sep 19 '13 at 18:02
  • `realloc` call `malloc` in case of NULL pointer, but I need "to determine whether a pointer refers to a static or auto variable, or to memory allocated" so it said @JohnBodу. Now for me problem is kind of solved. – Pycz Sep 19 '13 at 18:18
  • 1
    o their address range is different, stack addresses are generally, bigger. look at your architecture and figure out the range or VM addresses that should be your stack/auto variable range. – resultsway Sep 19 '13 at 18:25

1 Answers1

2

There's no portable way to determine whether a pointer refers to a static or auto variable, or to memory allocated via the *alloc functions, by looking at the pointer value alone. If you are intimately familiar with the memory model on your platform you could make some educated guesses, but that's about it.

Otherwise, if it matters, you will have to track that information yourself.

John Bode
  • 119,563
  • 19
  • 122
  • 198