What is wrong with this? - Prints correctly first time then memory corruption.

It prints correctly on the first try. The second attempt prints garbage.

#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <iomanip>
#include <limits>
#include <malloc.h>

using namespace std;

class Student
{
public:
char* name;
char* id;
Student();
~Student();
};

Student::Student()
{
name = (char*) malloc(sizeof(char)*51);
id = (char*) malloc(sizeof(char)*21);
}

Student::~Student()
{
free(name);
free(id);
}

std::ostream& operator<<(std::ostream &out, Student s)
{
out << s.name << " " << s.id << endl;
return out;
}

int main()
{
Student * students[50];
Student * student = new Student();
strcpy(student->name, "TEST");
strcpy(student->id, "1234");
students[0] = student;
for(int x = 0; x < 3; x++)
{
cout << *students[0] << endl;
}
}
Add the bold character:
std::ostream& operator<<(std::ostream &out, Student &s)
If you pass by copy, when the function return the local copy goes out of scope and releases its pointers, but because Student doesn't have a copy constructor, in doing so it also releases the pointers of the original, invalidating those pointers.
Topic archived. No new replies allowed.