我正在实施一个类来存储属于某个班级的学生列表。由于我使用char
数组来存储信息,我必须经常调整2D数组的大小。
然而,在我的测试软件中,当我调用以下两行时(参见第1节),内存显着增加。
Section 1
for(int i = 0; i < 1000;i++)
{
StudentClass studentClass;
studentClass.resizeArray(1000);
}
这是我的头文件......
#define NAME_SIZE 35
#define SUBJECT_SIZE 25
class StudentClass
{
private:
char name[NAME_SIZE];
int age;
char subject[SUBJECT_SIZE];
int numberOfStudents;
char **studentChar;
public:
StudentClass();
~StudentClass();
void setStudentName(char *name);
void setStudentAge(int age);
void setStudentSubject(char *subject);
void resizeArray(int n);
}
这是给内存泄漏的函数......
void StudentClass::resizeArray(int n)
{
int i;
int newStudentName=1;
char **temp;
if(n < 0)
{
cerr << "Number of students within a class can't be less than 0" << endl;
}
else if(n == numberOfStudents)
{
return;
}
else if(n == 0)
{
for (i=0; i<numberOfStudents; i++)
{
delete[] studentChar[i];
}
delete[] studentChar;
studentChar = NULL;
numberOfStudents = 0;
}
else
{
temp = new char*[n];
if(n < numberOfStudents)
{
for (i=0; i<n; i++)
{
temp[i] = studentChar[i];
}
for (; i<numberOfStudents; i++)
{
delete[] studentChar[i];
}
delete[] studentChar;
studentChar = temp;
numberOfStudents = n;
}
else
{
for (i=0; i<numberOfStudents; i++)
{
temp[i] = studentChar[i];
}
for (; i<n; i++)
{
temp[i] = new char[128];
sprintf(temp[i], "NewStudent_%02d", newStudentName++);
}
delete[] studentChar;
studentChar = temp;
numberOfStudents = n;
}
}
}
如果有人能让我知道为什么会有内存泄漏,我真的很感激。我真的很喜欢这些东西。
答案 0 :(得分:0)
刚刚使用Deleaker尝试了您的代码并获得了以下内容(a link to full sized image):
在析构函数中释放内存后,不再有内存泄漏(任务管理器证明):
~StudentClass()
{
resizeArray(0);
}