c++pointersmemory-managementdynamic-allocationstatic-allocation

Understanding basic dynamic allocation example


I have a very basic doute concerning dynamic allocation. Studying the tree following possible syntaxes I have been said that they all are dynamic allocations.

First:

int* px(nullptr); 
px = new int;
*px =20;

Then a more concise one:

int* px(nullptr);
px = new int(20);

Or even:

int*px(new int(20));

Then in a second moment in the same explanation I have been told that the third case is actually a static allocation. Than I got confused.

Is that true? Could someone explain me why please?

Many thanks.


Solution

  • Your first example:

    int* px(nullptr);
    px = new int;
    *px =20;
    

    The first line creates a stack allocated pointer and assigns it the value "nullptr". The second line creates an integer allocated on the heap and assigns px the pointer to that integer. The last line dereferences px and assigns 20 to the heap value.

    In your second example:

    int* px(nullptr);
    px = new int(20);
    

    The second line creates an int allocated on the heap with a value of 20 and assigns it's pointer to px.

    In your last example:

    int*px(new int(20));
    

    You're creating a heap allocated integer with value 20 and its pointer is passed back as an argument to initialize the integer pointer px. It's the same as:

    int* px = new int(20);
    

    So to answer your question, only the lines that contain "new" are dynamic memory allocation.

    new = heap allocated, otherwise it's stack allocated, unless you're calling a function/operator that uses new or malloc under the hood.