用new分配的内存到底该不该delete掉?

yndfcd 2002-12-20 03:19:47
部分代码如下:
HKEY hRoot,hSub;
hRoot = GetSelectedRoot();
if(RegOpenKeyEx( hRoot, strPath, NULL, KEY_QUERY_VALUE, &hSub))
{
*pResult = 0;
return;
}
while ( RegEnumKeyEx( hSub,
dwIndex,
NULL,
&dwSize,
NULL,
NULL,
NULL,
NULL) != ERROR_NO_MORE_ITEMS)
{
char* pBuffer = new char[dwSize++];
RegEnumKeyEx( hSub, dwIndex, pBuffer,
&dwSize,NULL, NULL, NULL, NULL);
tvis.item.pszText = pBuffer;
m_KeyTree.InsertItem( &tvis);
dwIndex++;
dwSize = 0;
}
RegCloseKey( hSub);
其中有两个问题,一、有人告诉我pBuffer应delete,请大家计论一下;
二、当hSub下没有子键时,仍会在TreeCtrl中插入一个子结点,为
什么?
...全文
50 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
yndfcd 2002-12-23
  • 打赏
  • 举报
回复
我现在已经有结论,new 的内存是一定要delete 掉的,不过肯定不能在树形控件存在时将其删除,否则,会导致错误,而应在程序结束时,将其删除。
枚举子键时,ERROR_NO_MORE_ITEMS只能确定是否枚举完所有子键,不能确定是否有子键,在没有子键时,返回值是某个ERRORCODE,不是ERROR_NO_MORE_ITEMS,这时应该用 RegEnumKeyEx() != ERROR_SUCCESS来判断.
则程序应改为:
while ( RegEnumKeyEx( hSub,
dwIndex,
NULL,
&dwSize,
NULL,
NULL,
NULL,
NULL) != ERROR_NO_MORE_ITEMS)
{
char* pBuffer = new char[dwSize++];
if(RegEnumKeyEx( hSub, dwIndex, pBuffer,
&dwSize,NULL, NULL, NULL, NULL)
!=ERROR_SUCESS)
{
delete [] pBuffer;
return;
}
tvis.item.pszText = pBuffer;
m_KeyTree.InsertItem( &tvis);
dwIndex++;
dwSize = 0;
}

并在析构函数中删除tvis.item.pszText所指向的内存.

demetry 2002-12-21
  • 打赏
  • 举报
回复
关键在于while中的条件判断,第一次枚举时,当没有子键时,返回值是不是是不是真的就是ERROR_NO_MORE_ITEMS——关键是第一次调用!
最好在调用之后用::GetLastErrotrr判断一下出现了什么错误,希望对你有所帮助
Hawk_lp 2002-12-21
  • 打赏
  • 举报
回复
char* pBuffer = new char[dwSize++];
ZeroMemory(pBuffer, dwSize);
RegEnumKeyEx( hSub, dwIndex, pBuffer,
&dwSize,NULL, NULL, NULL, NULL);
tvis.item.pszText = pBuffer;
m_KeyTree.InsertItem( &tvis);
dwIndex++;
dwSize = 0;
delete []pBuffer;
mjm_d 2002-12-21
  • 打赏
  • 举报
回复
如果你显式的使用了“new”你就一定要程序的某个部分将它给安全的“delete”掉,而且要保证它不会从别的途径跑掉
zhenxizhou 2002-12-20
  • 打赏
  • 举报
回复
至少应该在析构函数中把它释放,即使它不会导致很严重的问题,这也是一个好的编程习惯。
yndfcd 2002-12-20
  • 打赏
  • 举报
回复
But if I delete pBuffer,Where will the TreeCtrl get its display text?
Or where and when shall I delete them?
JiaoKoala 2002-12-20
  • 打赏
  • 举报
回复
Of course the pBuffer should be deleted. It is located from heap, and the system won't release the memory that allocated in heap. If u won't release it, no one will. So u will have a memory leak bug.
yndfcd 2002-12-20
  • 打赏
  • 举报
回复
上述问题中只要hSub下有至少一个子键,就不会有出现错误。只有在没有子键时才会出错。 作者声明。

15,979

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 界面
社区管理员
  • 界面
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧