Allocate Memory for Global Pointers
-
Hi, Is it correct to allocate and free memory for Global Pointers and also for global variable. eg code: ................. test.h typedef struct { int a; }test; ............... test.cpp include test.h int main() { test *T1; .. .. T1 = (struct test*)malloc(sizeof(struct test)+1);//??? .. free(T1);//??? } As far as my knowledge global variables is not in HEAP But Malloc will allocate space in HEAP. To ME it seems confusing... Can u guyz give some clear Ideas regarding this... Urs, -Pons ----------------------- The greatest of faults, I should say, is to be conscious of none.
-
Hi, Is it correct to allocate and free memory for Global Pointers and also for global variable. eg code: ................. test.h typedef struct { int a; }test; ............... test.cpp include test.h int main() { test *T1; .. .. T1 = (struct test*)malloc(sizeof(struct test)+1);//??? .. free(T1);//??? } As far as my knowledge global variables is not in HEAP But Malloc will allocate space in HEAP. To ME it seems confusing... Can u guyz give some clear Ideas regarding this... Urs, -Pons ----------------------- The greatest of faults, I should say, is to be conscious of none.
traapons wrote:
As far as my knowledge global variables is not in HEAP But Malloc will allocate space in HEAP.
You are actually right on both, but you are confused between a pointer variable and the memory it points to.
traapons wrote:
test *T1;
You declare a pointer variable on the stack. This declaration also says that this variable will be able to point to an instance of test structure.
traapons wrote:
T1 = (struct test*)malloc(sizeof(struct test)+1);//???
Now you allocate a memory chunk on the heap and assign its address to T1.
traapons wrote:
free(T1);//???
Finally, you use the pointer variable to free/deallocate that memory chunk on the heap. After the deallocation, T1 is still the original variable on the stack - it just doesn't point to that memory address any more. Hope this helps. Best, Jun
-
traapons wrote:
As far as my knowledge global variables is not in HEAP But Malloc will allocate space in HEAP.
You are actually right on both, but you are confused between a pointer variable and the memory it points to.
traapons wrote:
test *T1;
You declare a pointer variable on the stack. This declaration also says that this variable will be able to point to an instance of test structure.
traapons wrote:
T1 = (struct test*)malloc(sizeof(struct test)+1);//???
Now you allocate a memory chunk on the heap and assign its address to T1.
traapons wrote:
free(T1);//???
Finally, you use the pointer variable to free/deallocate that memory chunk on the heap. After the deallocation, T1 is still the original variable on the stack - it just doesn't point to that memory address any more. Hope this helps. Best, Jun