试图做一个简单的内存管理任务。我有一个名为 的类Vehicle,我试图重复将类 Vehicle 的一个实例分配给一个Vehicle *指针。但是,每当我尝试为指针赋值时,程序都会崩溃并显示以下输出:
munmap_chunk(): invalid pointer
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)
我int main()的很简单:
int main(int argc, char **argv)
{
Vehicle * ptrVehicle;
int d, w;
char input;
while (1) {
cout << "Enter q to quit, otherwise create vehicle object." << endl;
cin >> input;
if (input == 'q' || input == 'Q') {
break;
} else {
cout << "Enter the number of doors > \t";
cin >> d;
cout << endl << "Enter the numer of wheels > \t";
cin >> w;
cout << endl;
if (ptrVehicle) delete(ptrVehicle);
ptrVehicle = new Vehicle(w,d);
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
根据我的理解,如果 ptrVehicle 是一个非空指针,它指向的内存将被删除,以便可以创建一个新对象。但情况似乎并非如此。
您从未初始化过指针,delete未定义的行为也是如此。您可以在循环之前对其进行初始化。
Vehicle* ptrVehicle = nullptr;
Run Code Online (Sandbox Code Playgroud)