Search code examples
c++pointersstackheap-memorynew-operator

Live on heap or stack when use new operator within a function block?


For instance:

void Func()
{
    int* i = new int; // the simplest case

    vector<int*> v = new vector<int*>; // another case, not sure if **new** is using correctly here
    vector<int*>* vPointer = new vector<int*>; 
}

void main()
{
    Func();
}

So, if I allocate dynamic memory(by using new operator) for local variables in functions,

  1. Do they live on heap or stack?
  2. when the program exits the function, are they still dangling around on heap or destroyed as function variables?
  3. Can I use new operator on non-pointer types? How to delete (or return back the allocated heap memory) it later?

Thank you!


Solution

  • int i = 3;
    

    this creates an object of type int on the stack. (The C++ standard uses the term "automatic storage", and I'm usually a stickler for proper use of formal terms, but "stack" and "heap" are deeply embedded in programming vocabulary, so "stack" and "heap" are just fine as technical terms).

    int *ip = 0;
    

    this creates an object of type int* on the stack. ip holds a null pointer.

    int *ip = new int;
    

    this creates an object of type int* on the stack, just like the previous one. It holds a pointer to memory on the heap (see earlier parenthetical; the formal term is "free store"). You know that the memory is on the heap because that's what operator new does.

    When you're finished with the heap memory you have to release it:

    delete ip;
    

    if you don't delete it and the function that created it returns, the local variable (ip) that held the pointer is gone. The memory has been allocated and it hasn't been freed, so unless you copied the pointer to some place else, you have no way to get at the memory you allocated. That's called a "memory leak".