New_delete

Dynamic memory allocation: new and delete

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;


void leak(){
    int* q=new int;
    *q=1;
}

int main(){
    int* p;
    p = new int; //allocated on heap (only way possible to reference this newly allocated memory is
                 //through the pointer p. Possible pitfall. Every new requires a corresponding delete
    *p=5;
    cout<<p<<endl;
    cout << *p <<endl;
    delete p;
    p=nullptr; // p=0;
    cout<<p<<endl;
    leak(); //memory leak function
    /*
    cout << *p <<endl; //read memory
    *p=4; //writing to memory
    cout << *p <<endl;
    */

    return (0);
} // all memory freed on stack