1

I know that when I create a pointer and use malloc() to allocate some chunk of memory, that memory is located in the heap. Where is the pointer itself stored? Is it in the stack like any other variable? If so, does that mean that it is also affected by scope (ie, if created inside loop, it can't be accessed by name outside the loop)?

0

Where is the pointer itself stored? Is it in the stack like any other variable? If so, does that mean that it is also affected by scope (ie, if created inside loop, it can't be accessed by name outside the loop)?

well, it depends on where/how the pointer is declared. if the pointer is a local variable, then yes -- it's stored on the stack and goes out of scope as its scope ends. in fact, this is one way how you can leak the memory. for example:

if (1) // executes anyway
    // allocate memory for an int to be pointed to by p
    int *p = malloc(sizeof(int));

/* p is out of scope here and you can NEVER free the
   memory that you've allocated above */

if you ran valgrind, you'd see a message like

LEAK SUMMARY:
    definitely lost: 4 bytes in 1 blocks
3
  • But, you can always create a pointer outside the loop (or even as a global variable in those rare cases where it is appropriate) and set it to null initially, and then use it in a malloc later. You just need to be careful to make sure that you don't lose track of memory through reassignment later. If you do reassign, the previously malloc'd memory has to be tracked somehow, such as in a linked list. – Cliff B May 28 '15 at 17:50
  • @Kareem: Ok great. That makes sense. Help me out with one more part that I may just not be thinking clearly on. Why the (int *) before the malloc() call? – reddisht May 28 '15 at 19:02
  • @reddisht this is a type cast operator. I shouldn't have put it there really since it's unnecessary and could cause problems in this situation. but good in case you didn't know such thing existed -- you can read more about it now. – kzidane May 28 '15 at 19:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .