Overload new and delete operator to manipulate objects of Student class.Class Student must contain data members like char * name,int roll_no,int branch etc.The overloaded new and delete operator must allocate and deallocate memory for the student class object and its data members.
Here is my code. The problem is that I'm getting some runtime error after reading the roll number of 2nd student record. I'll have to admit that I dont really understand the overloaded functions arguments properly. Please help me

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<new>
#include<string.h>
using namespace std;
class student
{
	char *name,*branch;
    int rno;
	public:
	student()
	{

	}
	student(char n[],int r,char br[])
	{
        strcpy(name,n);
		rno=r;
        strcpy(branch,br);
    }
	void putdata();
	void *operator new(size_t size);
	void operator delete(void *p);
};
void *student::operator new(size_t size)
{
	void *p;
	p=malloc(size);
	return p;
}
void student::operator delete(void *p)
{
	free(p);
}
void student::putdata()
{
	cout<<"\nName :   "<<name<<"\nRoll No :    "<<rno<<"\nBranch   : "<<branch;
}
int main()
{
    int n;
	int rno;
	char bra[10],name[10];
	student *s[10];
	cout<<"\nenter the no. of students:";
	cin>>n;
	for(int i=0;i<n;i++)
	{
		cout<<"\nenter name:";
		cin>>name;
		cout<<"\nenter roll no:";
		cin>>rno;
		cout<<"\nenter branch:";
		cin>>bra;
		s[i]=new student(name,rno,bra);
	}
	cout<<"\nstudent details\n";
	for(int i=0;i<n;i++)
	{
		s[i]->putdata();
		delete s[i];
	}
	return(0);
}

Recommended Answers

All 2 Replies

You never allocate the memory for the name and branch variables, so when you copy the strings to them, they end up writing to random locations in memory. Add the following to the new and delete operators and it should fix the issue:

void *student::operator new(size_t size)
{
	void *p;
	p = malloc(size);
	(reinterpret_cast<student *>(p))->name = reinterpret_cast<char *>(malloc(16));
	(reinterpret_cast<student *>(p))->branch = reinterpret_cast<char *>(malloc(5));
	return p;
}

void student::operator delete(void *p)
{
  	free(reinterpret_cast<void *>(reinterpret_cast<student *>(p)->name));
  	free(reinterpret_cast<void *>(reinterpret_cast<student *>(p)->branch));
	free(p);
}

WOW! Thanks a lot! It is working. Came to know reinterpret_cast also. Problem solved

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.