View Full Version : Where is pointer located
camel-man
Jan24-12, 02:11 PM
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.
Mech_Engineer
Jan24-12, 02:20 PM
LMGTFY: https://www.google.com/search?q=IS+a+pointer+in+C+located+on+the+stack+or +heap&rls=com.microsoft:en-us&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1&safe=on
The answer is basically, it depends. See here:
http://answers.yahoo.com/question/index?qid=20080726212552AAPVgMH
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.
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.
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.
camel-man
Jan24-12, 06:04 PM
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?
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?
Yes, that is correct.
vBulletin® v3.8.7, Copyright ©2000-2012, vBulletin Solutions, Inc.