I have class named "Student" with 3 members.
In addition, I have 2 functions, SetName
and Operator=
.
class Student
{
private:
int ID;
char* name;
Faculty faculty;
public :
bool SetName(const char* other);
};
typedef enum { ENGINEERING, MEDICINE, HUMANITIES, MANAGEMENT, GENERAL } Faculty;
bool Student::SetName(const char * other)
{
if (!other)
return false;
char* temp;
temp = new char[strlen(other) + 1];
if (!temp)
return false;
//if (this->name)
// delete[]name;
std::string s = other;
name = temp;
memcpy(name,other,strlen(other) + 1);
return true;
}
Student& Student::operator=(const Student &other)
{
this->ID = other.ID;
this->faculty = other.faculty;
this->SetName(other.name);
return *this;
};
Of course, I have default and copy destructor. There is a problem with the "SetName" Function, but When I run valgrind, it tells me -
==4661== HEAP SUMMARY:
==4661== in use at exit: 72,710 bytes in 2 blocks
==4661== total heap usage: 47 allocs, 45 frees, 74,410 bytes allocated
==4661==
==4661== 6 bytes in 1 blocks are definitely lost in loss record 1 of 2
==4661== at 0x4C2E80F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4661== by 0x402798: Student::SetName(char const*) (in /home/noam/Desktop/Avoda3/temp/myStudentSet)
==4661== by 0x40264E: Student::Student(Student const&) (in /home/noam/Desktop/Avoda3/temp/myStudentSet)
==4661== by 0x4011D6: StudentSet::Add(Student const&) (in /home/noam/Desktop/Avoda3/temp/myStudentSet)
==4661== by 0x400F1D: StudentSet::StudentSet(Student const*, int) (in /home/noam/Desktop/Avoda3/temp/myStudentSet)
==4661== by 0x4020B6: main (in /home/noam/Desktop/Avoda3/temp/myStudentSet)
==4661==
==4661== LEAK SUMMARY:
==4661== definitely lost: 6 bytes in 1 blocks
==4661== indirectly lost: 0 bytes in 0 blocks
==4661== possibly lost: 0 bytes in 0 blocks
==4661== still reachable: 72,704 bytes in 1 blocks
==4661== suppressed: 0 bytes in 0 blocks
==4661== Reachable blocks (those to which a pointer was found) are not shown.
==4661== To see them, rerun with: --leak-check=full --show-leak-kinds=all
When I try to remove the comment and add
if (this->name)
delete[]name;
to the SetName
function, I have much more problems.
I don't have any idea how to solve this. Can someone help me or give a hint?