If memory needs to exist for longer than the lifecycle of the function, we must use heap memory

int *allocate_an_integer() {
    int *i = new int;
    *i = 0;
    return i;
}

Below is the error case with stack memory.

int *allocate_an_integer() {
    int i = 0;
    return &i;
}

int main() {
    int *j;
    j = allocate_an_integer();
    int k = *j;
    return 0;
}

What value is variable k assigned and why?


Unknown. 
Depending on the compiler settings, the compiler may report that a local variable address is being returned, which could be treated as a warning or as a compilation error; 
Or, if the program is allowed to compile, then at runtime the variable k could be assigned zero, or some other value, or the program may terminate due to a memory fault.

The only way to create heap memory is C++ is with the new operator.

The new operator returns a pointer to the memory storing the data - not an instance of the data itself.

The new operator in C++ will always do three things:

  1. Allocate memory on the heap for the data structure
  2. Initialize the data structure
  3. Return a pointer to the start of the data structure

The memory is only every reclaimed by the system when the pointer is passed to the delete operator.

int * numPtr = new int;

The code above allocates two chunk of memory: