VC++申请和释放内存问题(常发生在C code 转 VC++时)
VC++环境下,用 malloc 申请内存空间的代码如下:
点击查看代码
linkqueue p = (linkqueue)malloc(sizeof(linkqueue));
if (p == NULL) {
printf("fun(CreateQueue):malloc linkqueue failed\n");
}
linklist q = (linklist)malloc(sizeof(linknode));
if (q == NULL) {
printf("fun(CreateQueue):malloc linklist failed\n");
}
if(q != NULL)
q->data = 0;
q->next = p->rear;
cout << q << " " << p << " " << p->front << " " << p->rear << " " << endl;
p->front = q;
p->rear = q;
cout << q << " " << p << " " << p->front << " " << p->rear << " " << endl;
p->rear = q->next;
if (q != NULL) {
free(q);
cout << "FreeQueue:Clear linknode" << endl;
}
if (p != NULL) {
free(p);
cout << "FreeQueue:Clear linkqueue" << endl;
}
return;
编译显示成功,但在执行释放内存代码 free(p); free(q); 时报错。
经过分析发现,p是结构体linkqueue指针, linkqueue结构体中有两个指针变量front,rear,在队列为空时,front和rear 都指向头节点 q .
Debug 发现,当释放p内存空间时,会先释放 front , 再释放 rear 时,由于 rear指向的空间已由 front 释放了,所以提示出错,程序执行卡住 。
而在释放 p 之前,只要把 p->rear 指针赋未定义空间初值,则程序可顺利执行,debug 代码如下:
因此,确定是 p->rear 释放时出错。解决方案是申请内存空间和释放内存改由 new 和 delete 完成,代码修改如下:
点击查看代码
linkqueue CreateQueue() {
/*
* CreateQueue : Create a new linkqueue and initialize
* Para :non a
* @ret : return the pointer of new linkqueue
*/
linkqueue p = new linkqueue_t;
linklist q = new linknode;
if((p == NULL) || (q == NULL)) {
printf("fun(CreateQueue):malloc failed\n");
return NULL;
}
//initialize
q->data = 0;
q->next = NULL;
p->front = q;
p->rear = q;
return p;
}
linkqueue FreeQueue(linkqueue L) {
/*
* FreeQueue : Release linkqueue from memory
* Para :linkqueue L
* @ret : NULL
*/
if(L->rear != L->front){
ClearQueue(L);
cout << "FreeQueue:Clear queue" << endl;
}
if(L->front != NULL){
delete L->front;
cout << "FreeQueue:Clear head" << endl;
}
if (L != NULL){
delete L;
cout << "FreeQueue:Clear linkqueue" << endl;
}
return NULL;
}
编译测试 pass , 把执行结果和指针结构整理呈现如下: