【发布时间】:2016-12-10 04:33:29
【问题描述】:
我有错误提示 对象 0x7ffbaf002000 错误:未分配指针被释放。但是我已经打印出内存地址,它确实是在 0x7ffbaf002000 之前在循环内的函数allocFlights(Flight**, int)flight[0] = (Flight*) malloc(sizeof(Flight) * 60) 中分配的。所以我在函数deAllocFlights(Flight**, int) 中打印出std::cout << flight[0] << std::endl 的内存地址,看看它是否存在,它是否存在于循环内的0x7ffbaf002000
我不明白我为什么会遇到这个问题。我还是 C++ 新手。
这是飞行结构:
typedef struct {
int flightNum;
char origin[20];
char destination[20];
Plane *plane;
}Flight;
void getAllFlights(Flight **flight) {
FILE *file = fopen("reservation.txt", "r");
int i = 0, totalFlights;
if(file == NULL)
{
perror("Error in opening file");
}
fscanf(file, "%d\n", &totalFlights);
*flight = (Flight*) malloc(sizeof(Flight*) * totalFlights);
allocFlights(flight, totalFlights); // Allocate here
.
.
.
deAllocFlights(flight, totalFlights); // Error: Deallocate here
fclose(file);
}
函数 allocFlights
void allocFlights(Flight **flight, int totalFlights) {
for (int i = 0; i < totalFlights; i++) {
flight[i] = (Flight*) malloc(sizeof(Flight) * 60);
std::cout << flight[i] << " " << i << std::endl; // Print out memory address
}
}
函数deallocFlights
void deAllocFlights(Flight** flight, int totalFlights) {
for (int i = 0; i < totalFlights; i++) {
std::cout << flight[i] << " " << i << std::endl; // Print out memory address
free (flight[i]);
}
}
主要:
int main() {
Flight *flight;
getAllFlights(&flight);
free(flight);
return 0;
}
【问题讨论】:
-
选择一个:C 或 C++。这可以为您简化很多事情。
-
没有像 C/C++ 这样的语言。这是 C++
-
请注意,您的代码是 C++,因为您使用
std::cout << flight[i] << …。但是,如果您使用 C++ 编码,则不应使用malloc()和free()— 如果您必须显式管理内存,则应使用 C++ 的高级new和delete运算符。跨度> -
注意
perror()不会退出,所以如果你打开文件失败,你检查并报告你失败了(好),然后继续使用空文件流,这不会带来幸福。 -
如果
Flight是非 POD 类型,即使您获得了要编译的代码,这些代码都不起作用。原因是您不能在此类类型上使用malloc或free,因为您没有构造对象。放弃这种类型的编码并使用std::vector和 C++ 提供的其他容器(并为自己找一本更好的 C++ 书籍/老师/无论你从哪里学习 C++)。