删除char **数组时出现内存泄漏 [英] I am getting memory leak while deleting char ** array

查看:97
本文介绍了删除char **数组时出现内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在使用以下代码为char** dbNames分配内存.
总计数没有.的名称

Hi,
I am using the following code to allocate the memory for char** dbNames.
There are a total count no. of names

dbNames = new char*[count];
for(int i=0;i<count;i++)
{
  fscanf(imgListFile,"%s";,imgFilename);
  dbNames[i]=new char[strlen(imgFilename+1)];
  strcpy(dbNames[i],imgFilename);
}


它工作正常,但是在删除时我正在使用以下代码
其中countgCount相同.


It works fine but at the time of deleting I am using following code
where count and gCount are the same.

for(int i=0;i<gCount;i++)
{
  if(dbNames[i])
  {
    delete [] dbNames[i];
    dbNames[i] = NULL;
  }
}


但是它会引发异常,并警告说堆将被破坏.
有人可以建议我释放内存的正确解决方案吗?

谢谢&问候
Ramkrishna


But it throws the exception and gives the warning that heap will be corrupt.
Can anybody suggest me the proper solution to free the memory?

Thanks & Regards
Ramkrishna

推荐答案

只是一个建议-使用std::vector<std::string>而不是char**并省去您的麻烦. ;)
Just an advice - use std::vector<std::string> instead of char** and forget about your troubles. ;)


看看这行
ramkrishna.jangale写道:
ramkrishna.jangale wrote:

dbNames [i] = new char [strlen(imgFilename + 1)];

dbNames[i]=new char[strlen(imgFilename+1)];


尝试将其更改为


Try to change it to

dbNames[i]=new char[strlen(imgFilename) + 1];



如果imgFilenamechar *,则将指针移动一个char到末尾,并且strlen()的结果比字符串长度小1个字节.因此,为文件名分配的所有内存块都太小了两个字节,而没有必要按尾随零增加一个字节.



If imgFilename is a char * you move the pointer one char to the end and the result of strlen() is 1 byte less than the string length. So all allocated memory blocks for the filenames are two bytes too small, and not as needed one byte bigger for the tailing zero.


由于您只发布了分配和删除代码,因此可以仅假设您以某种方式破坏了其他地方的这些指针之一.尝试使用调试器单步执行代码,以查看指针是否仍然有效.
Since you have only posted the allocation and deletion code, one can only assume that you have somehow corrupted one of these pointers elsewhere. Try stepping through the code with the debugger to see whether your pointers are still valid.


这篇关于删除char **数组时出现内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆