【发布时间】:2013-02-17 07:01:03
【问题描述】:
您好,我有一个关于 C++ 内存管理的一般查询。 只有在这个程序的帮助下,我才知道 new 用于在堆上分配内存,临时变量在堆栈上分配内存。如果我们在堆上分配内存,我们也必须手动释放它,否则会出现内存泄漏.
但是在程序中,我通过在堆上创建一个 BST 类型的新变量 temp 来更新名为 Insert 的函数中的 BST 结构对象。但是我不确定如何释放该内存。如果我使用 free 命令在函数结束时,即 free(temp) 然后存储在该内存中的值将丢失,如果我再次尝试访问它,我会得到一个错误,我当然不能在 main 中使用 free(temp),因为它不是main 的局部变量。 谁能告诉我应该怎么做。
顺便说一句,我必须提到,如果不使用 free(temp),我的程序也可以正常工作,但是我猜内存泄漏正在发生,这很糟糕。
我也有点困惑,如果我评论析构函数~BST(),但当我取消注释时给出链接器错误,为什么我的程序运行没有错误。
#include<iostream>
#include<string>
#include<conio.h>
#include<array>
#include<stack>
#include<sstream>
#include<algorithm>
#include<vector>
#include<ctype.h>//isdigit
#include<deque>
#include<queue>
#include<map>
using namespace::std;
struct BST
{
int data;
BST *left;
BST *right;
BST(int d,struct BST* l,BST *r):data(d) , left(l) ,right(r)
{
}
BST()
{
}
//~BST();
};
void levelOrder(struct BST *root)
{
struct BST *temp=NULL;
int count =0;
deque<struct BST*> dq;
if(!root)
{
return;
}
dq.push_back(root);
count=dq.size();
while(!dq.empty())
{
temp=dq.front();
cout<<temp->data<<" ";
if(temp->left)
{
dq.push_back(temp->left);
}
if(temp->right)
{
dq.push_back(temp->right);
}
dq.pop_front();
if(--count==0)
{
cout<<endl;
count=dq.size();
}
}
}
void Insert(struct BST*root,int data)
{
//struct BST temp(data,NULL,NULL);
BST *temp = new BST(data,NULL,NULL);
temp->data =data;
temp->left= NULL;
temp->right=NULL;
if(!root)
{
return;
}
while(root)
{
if((root)->data >data)
{
(root)=(root)->left;
if(!(root)->left)
{
(root)->left=temp;
break;
}
}
else
{
(root)=(root)->right;
if(!(root)->right)
{
(root)->right=temp;
break;
}
}
}
}
int main()
{
deque<struct BST> dq1,dq2;
BST e(4,NULL,NULL);
BST f(3,NULL,NULL);
BST d(1,&f,NULL);
BST b(2,&d,&e);
BST c(8,NULL,NULL);
BST a(6,&b,&c);
levelOrder(&a);
Insert(&a,5);
cout<<a.left->right->right->data;
cout<<endl;
levelOrder(&a);
_getch();
return 0;
}
【问题讨论】:
-
这比惯用的 C++ 更像 C-in-C++。您的
struct BST应该是一个类,并且应该将Insert作为成员函数。上个世纪的裸指针太棒了。如果您使用类似于std::unique_ptr和/或std::shared_ptr的东西,您的内存泄漏问题就会消失。
标签: c++ pointers free new-operator destructor