Yes, there are multiple memory leaks.
Code:
class Student{
private:
char* name;
int* marks;
public:
Student(char * n, int* a){
name = new char[10]();
marks = new int[3]();
//!! Both the above allocations are leaks, since you just overwrite your pointers.
//!! Also, having a pointer to something on the outside is VERY bad style.
//!! You have no control over how it was allocated (if at all), and no control
//!! over it's lifecycle. It could disappear without warning, leaving you with a
//!! stale (or dangling) pointer.
name = n;
marks = a;
}
~Student(){
cout << "Destructor called" << endl;
delete name;
//!! name was allocated with [], so you need to use delete[]
//!! well, you would, if you fixed your ctor to do the right thing and make
//!! copies of the inputs.
//!! As is, it's just plain BROKEN because name was created with malloc
//!! and not new.
delete[] marks;
}
void display(){
cout << "Name : " << name << endl;
cout << "Subject marks : " << endl;
for(int i=0; i<3; i++) {
cout << marks[i] << endl;
}
}
};
int main(){
// Name
//!! Don't use malloc to allocate memory in C++ programs
//!! malloc doesn't cause the ctor to be called.
//!! Whilst technically, it's OK for a PoD type, it's not a habit
//!! you want to cultivate.
char* name = (char*) malloc(sizeof(char)*10);
strcpy(name,"Alan");
// Marks
int* marks = new int[3];
marks[0] = 23;
marks[1] = 20;
marks[2] = 40;
Student *s1 = new Student(name, marks);
s1->display();
delete s1;
return 0;
}
> I saw this code posted on what seems to be a reputable blog
Please tell us, so we can go and have a good laugh...