且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除char **数组时出现内存泄漏

更新时间:2022-05-28 20:57:56

只是一个建议-使用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.