ISourceCode

Make the frequent cases fast and the rare case correct

Program to illustrate difference between new and malloc

This is a simple program to illustrate difference between new and malloc using constructors and destructor.

laptop:~/code$ cat dynamicmem.cpp 
//Program to demonstrate difference between new and malloc
#include <iostream>
#include <malloc.h>
#include <new>
using namespace std;
class test
{
	public:
	test(){cout<<"Constructor function called"<<endl;}
	~test(){cout<<"Destructor function called"<<endl;}
};
int main()
{
	test *k,*j;// declare pointers to class text
	test w;//declare a variable test to investigate constructor functions
	cout<<"at point 1"<<endl;
	j = new test[4];//request an array of class objects of size 9
	cout<<"at point 2"<<endl;
	k=(test *)malloc(4*sizeof(test));//request an array
	cout<<"at point 3"<<endl;
	delete[] j;// give back memory allocated to the machine
	cout<<"at point 4"<<endl;
	free(k);//give back memory allocated to the machine
	cout<<"at point 5"<<endl;
	return 0;
}

OUTPUT:

laptop:~/code$ ./a.out
Constructor function called
at point 1
Constructor function called
Constructor function called
Constructor function called
Constructor function called
at point 2
at point 3
Destructor function called
Destructor function called
Destructor function called
Destructor function called
at point 4
at point 5
Destructor function called

One response to “Program to illustrate difference between new and malloc

  1. pavithra September 9, 2015 at 8:29 pm

    I about now stack operation thank you

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: