Thursday, 21 September 2017

New and delete in C++

/*
 New Delete Demo in C++
*/
#include "iostream"
#include <new> // Some time you may have to include this file

using namespace std;

int main(){
 int *var = new int(10); //allocating single block of memory and initializing there only
 cout<<"\nVar: "<<*var;
 *var = 50;
 cout<<"\nVar: "<<*var;
 cout<<endl;

 int *foo = new (std::nothrow) int[3];
 /*
  -- if memory allocation fails, then bad_alloc exception is thrown by system.
  -- or explicitely nullptr can be checked in 'nothrow' is used
  
 */
 if(foo == nullptr) // for nullptr to work compile code "g++ -std=c++0x program.cpp" else use "NULL" rather "nullptr"
  cout<<"\n Memory allacation failed ";
 else{
 /* even values can be initialized using loop */
 // Different way by which foo is initialized 
  *foo = 20;
  *(foo+1) = 30;
  foo[2] = 40;
  
  cout<<" "<<*foo<< " "<<foo[1]<<" "<<foo[2]<<endl;
 }
 delete var; //deallocating memory
 delete []foo;
 return 0;
}
/*
 OUTPUT
[pavan@localhost Home]$ g++ -std=c++0x NewDelete1.cpp
[pavan@localhost Home]$ ./a.out 

Var: 10
Var: 50
 20 30 40
[pavan@localhost Home]$ 

*/

No comments: