【发布时间】:2016-01-16 06:07:26
【问题描述】:
我正在为学校做作业,我们正在做内存管理。到目前为止,我们的任务基本上只是创建一个学生 + id 的列表,并且我们将动态地完成它。
我还应该重载删除/新建运算符,我已经完成了。但是,在测试我的程序时它会崩溃,可能不会创建数组来分配信息。
namespace
{
char buffer[1024];
int allocated = 0;
}
struct student
{
int size;
char *firstname;
char lastname;
int studentId;
int occupied;
student::student() : size(0)
{
}
student::student(int s) : size(s)
{
std::cout << "constructor" << std::endl;
std::cout << "Allocated: " << allocated << std::endl;
int currentLoc = allocated;
allocated += s;
firstname = new (&buffer[currentLoc]) char[s];
}
void *student::operator new(size_t s)
{
std::cout << "Operator new allocated: " << allocated << std::endl;
int currentLoc = allocated;
allocated += s;
return &buffer[currentLoc];
}
void student::operator delete(void *ptr)
{
std::cout << "Delete called " << std::endl;
std::free(ptr);
}
student::~student()
{
}
};
int main(int argc, char** argv)
{
student *studentlist = new student[5];
for (int i = 0; i < 5; ++i)
{
std::cout << "Fill in the first name for the student." << std::endl;
std::cin >> studentlist[i].firstname;
std::cout << "Fill in the last name for the student." << std::endl;
std::cin >> studentlist[i].lastname;
studentlist[i].studentId = (rand() % (9999 - 999)) + 999;
studentlist[i].occupied = 1;
}
return 0;
}
修改为当前版本
【问题讨论】:
标签: c++ arrays dynamic allocation