[英]Memory Leak (char[])
When I run my program, it can run for a while, then all of the sudden, it experiences a huge memory leak. 当我运行程序时,它可能会运行一段时间,然后突然间,它将遇到巨大的内存泄漏。 I traced it out using a snapshot of the heap when it crashed, and I have a mysterious char[] with the size of 232,023,801 Bytes. 我使用堆崩溃时的快照对其进行了跟踪,并且我有一个神秘的char [],其大小为232,023,801字节。 The minutes preceding crash have no unusual behavior until then. 直到崩溃发生的前几分钟,都没有异常行为。 The only places where I use char arrays is in the following piece of code: 我使用char数组的唯一地方是以下代码:
string ReadString(DWORD64 addr) {
char* buffer = new char[128];
bool validChar = true;
for (int c = 0; c < 128 && validChar; c++) {
buffer[c] = Mem.Read<char>(addr+ (0x1 * c), sizeof(char));
if (!isalnum(buffer[c]) && !ispunct(buffer[c]))
validChar = false;
}
string ret= string(buffer);
delete[] buffer;
return ret;
}
All this code should be doing is reading a few characters from memory, saving the char array to a string, cleaning up the array, and returning the string. 这些代码应该做的就是从内存中读取一些字符,将char数组保存为字符串,清理该数组,然后返回该字符串。 How is the memory leak originating from here? 内存泄漏是如何产生的? Or does the char[] in the heap snapshot potentially point to another issue? 还是堆快照中的char []可能指向另一个问题?
Assuming that string
here is std::string
: 假设这里的string
是std::string
:
You call string(buffer)
which assumes that buffer
is 0-terminated and allocates a new string. 您调用string(buffer)
,它假定buffer
是0终止的,并分配了一个新字符串。 But your code doesn't ensure that buffer
is actually 0-terminated, so this can cause undefined behavior, including potentially crashing or allocating too much memory for the string. 但是您的代码不能确保buffer
实际上是0终止的,因此这可能导致未定义的行为,包括潜在的崩溃或为字符串分配过多的内存。
You probably want to use the string(buffer, size)
constructor instead, which doesn't require buffer
to be 0-terminated. 您可能想改用string(buffer, size)
构造函数,该构造函数不需要buffer
以0结尾。
I'd also recommend avoiding the manual new
/ delete
. 我也建议您避免手动进行new
/ delete
。 One way to do this is to create an empty string and push_back
the characters you read to it. 一种实现方法是创建一个空字符串,并将输入的字符push_back
回读。 This avoid the need for buffer
. 这样可以避免使用buffer
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.