Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Where is pointer located

  1. Jan 24, 2012 #1
    IS a pointer in C located on the stack or heap? Also if you declare a pointer in a function then malloc the memory for it does that mean it is both on the stack and heap because it is a local variable but it is also dynamic memory.
  2. jcsd
  3. Jan 24, 2012 #2


    User Avatar
    Science Advisor
    Gold Member

  4. Jan 24, 2012 #3


    User Avatar

    Staff: Mentor

    The pointer is on the stack. The block of data that it points to is on the heap. They are two different objects, although obviously related.
  5. Jan 24, 2012 #4


    User Avatar
    Homework Helper

    A pointer is the same as any variable, it could be global, static, on the stack, or possibly on the heap (for example, malloc memory for an array of pointers...). A pointer can point to any variable type, and a pointer to function points to code.
  6. Jan 24, 2012 #5
    Ok thank you I think I got it. Tell me if I am on track or not

    HEAP: int *x=malloc(5); <--- x is on stack but points to heap
    STACK: int *x,y; x=&y; <--- x is on stack again and points to memory on the stack

    so unless the int *x; is global it will be on stack correct?
  7. Jan 24, 2012 #6
    Yes, that is correct.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook