4

Ok, so I did find some questions that were almost similar but they actually confused me even more about pointers.

C++ Pointer Objects vs. Non Pointer Objects

In the link above, they say that if you declare a pointer it is actually saved on the heap and not on the stack, regardless of where it was declared at. Is this true ?? Or am I misunderstanding ??? I thought that regardless of a pointer or non pointer, if its a global variable, it lives as long as the application. If its a local variable or declared within a loop or function, its life is only as long as the code within it.

Community
  • 1
  • 1
numerical25
  • 10,524
  • 36
  • 130
  • 209

7 Answers7

12

The variable itself is stored on the stack or DATA segment, but the memory it points to after being allocated with new is within the heap.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 4
    Ok, so when you create a pointer within a local scope. You create memory on the stack that points to a space on the heap. At the end of the scope. the memory on the stack is removed and the memory on the heap remains ?? – numerical25 Jun 02 '10 at 00:11
  • Correct. To get rid of the heap space, you use `delete`. – Amber Jun 02 '10 at 00:12
  • So is it crucial to use delete ??? Or Is it possible to find those pointers and delete them later ? – numerical25 Jun 02 '10 at 00:22
  • Some allocators keep track of leaked heap space. Most do not. – Ignacio Vazquez-Abrams Jun 02 '10 at 00:26
  • 2
    And by *smart pointer*, we mean a pointer that deallocates the heap space it points to when it itself goes out of scope. – David R Tribble Jun 02 '10 at 00:31
  • @Loadmaster, it is probably good to include explanation on the ownership passing and reference counting which lead to deleting or not. – YeenFei Jun 02 '10 at 01:18
  • 1
    @numerical25: In general, if you yourself are calling `new`, then you yourself also probably need to call `delete`. – Amber Jun 02 '10 at 01:57
9
void main()
{
  int* p;          // p is stored on stack
  p = new int[20]; // 20 ints are stored on heap
}
// p no longer exists, but the 20 ints DO EXSIST!

Hope that helps.

Kornel Kisielewicz
  • 55,802
  • 15
  • 111
  • 149
  • Yes that does make sense. It's crazy, I've been reading books on C++, and reading the Cplusplus primer. And Some how I manage to miss how pointers are stored. They gave a overview on the scope of variables and I kind of took it that pointers were the same way. So what if you have 20 ints on the stack with nothing pointing to it. is it possible to find them and remove them. Or is it crucial to just delete them at the end of the scope – numerical25 Jun 02 '10 at 00:19
  • 1
    "So what if you have 20 ints on the stack with nothing pointing to it. is it possible to find them and remove them. Or is it crucial to just delete them at the end of the scope"...... You mean 20 ints on the heap, as in Kornel's example - you must "delete []" them. If he would declare them on the stack then no, no delete would be required since no new was used (: – Poni Jun 02 '10 at 00:24
  • Google for some info about stack memory. Once you get the idea you can't be confused. – Poni Jun 02 '10 at 00:24
7
void func()
{
  int x = 1;
  int *p = &x;
}
// p goes out of scope, so does the memory it points to

void func()
{
  int *p = new int;
}
// p goes out of scope, the memory it points to DOES NOT

void func()
{
  int x = 1;
  int **pp = new int*;
  *pp = &x;
}
// pp goes out of scope, the pointer it points to does not, the memory it points to does

And so forth. A pointer is a variable that contains a memory location. Like all variables, it can be on the heap or the stack, depending on how it's declared. It's value -- the memory location -- can also exist on the heap or the stack.

Typically, if you statically allocate something, it's on the stack. If you dynamically allocate something (using either new or malloc) then it's on the heap. Generally speaking you can only access dynamically allocated memory using a pointer. This is probably where the confusion arises.

Niki Yoshiuchi
  • 16,883
  • 1
  • 35
  • 44
5

It is necessary to distinguish between the pointer (a variable that holds a memory location) and the object to which the pointer points (the object at the memory address held by the pointer). A pointer can point to objects on the stack or on the heap. If you use new to allocate the object, it will be on the heap. The pointer can, likewise, live on the heap. If you declare it in the body of a function, then it will be a local variable and live in local storage (i.e. on the stack), whereas if it is a global variable, it will live somewhere in your application's data section. You can also have pointers to pointers, and similarly one can allocate a pointer on the heap (and have a pointer-to-a-pointer pointing to that), etc. Note that while I have referenced the heap and stack, the C++ only mentions local/automatic storage and dynamic storage... it does not speak to the implementation. In practice, though, local=stack and dynamic=heap.

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
2

A pointer is a variable containing the address of some other object in memory. The pointer variable can be allocated:

  • on the stack (as a local auto variable in a function or statement block)
  • statically (as a global variable or static class member)
  • on the heap (as a new object or as a class object member)

The object that the pointer points to (references) can likewise be allocated in these three places as well. Generally speaking, though, a pointed-to object is allocated using the new operator.

Local variables go out of scope when the program flow leaves the block (or function) that they are declared within, i.e., their presence on the stack disappears. Similarly, member variables of an object disappear when their parent object goes out of scope or is deleted from the heap.

If a pointer goes out of scope or its parent object is deleted, the object that the pointer references still exists in memory. Thus the rule of thumb that any code that allocates (news) an object owns the object and should also delete that object when it's no longer needed.

Auto-pointers take some of the drudgery out of the management of the pointed-to object. An object that has been allocated through an auto_ptr is deleted when that pointer goes out of scope. The object can be assigned from its owning auto_ptr to another auto_ptr, which transfers object ownership to the second pointer.

References are essentially pointers in disguise, but that's a topic for another discussion.

David R Tribble
  • 11,918
  • 5
  • 42
  • 52
  • +1. Everyone forgets that variables are defined where they are used. If they are member variables of a class - they can be on the stack or on the heap with the instance of the class. – Igor Zevaka Jun 02 '10 at 03:33
0

I thought that regardless of a pointer or non pointer, if its a global variable, it lives as long as the application. If its a local variable or declared within a loop or function, its life is only as long as the code within it.

That's true.

they say that if you declare a pointer it is actually saved on the heap and not on the stack

That's wrong, partially. You can have a pointer on the heap or the stack. It's a matter of where and how you declare it.

void main()
{
    char c = 0x25;
    char *p_stack = &c; // pointer on stack

    StructWithPointer struct_stack; // stack
    StructWithPointer *struct_heap = new StructWithPointer(); // heap, thus its pointer member "p" (see next line) is also on the heap.
    struct_heap->p = &c; // pointer on heap points to a stack
}

... and, a compiler might decide to use a register for a pointer!

Poni
  • 11,061
  • 25
  • 80
  • 121
0

Looks like you need to grab the classic K&R C book and read through chapters 4 & 5 for thorough understanding of the differences between declaration and definition, scope of a variable and about pointers.

yasouser
  • 5,113
  • 2
  • 27
  • 41