[英]C++ function is leaking memory, I'm new to C++ and not sure how to fix it
I'm very new to C++ and is trying to compile a program, however it's leaking memory and this part of the code.我对 C++ 非常陌生,并且正在尝试编译程序,但是它正在泄漏 memory 和这部分代码。
char* ReadString(u_int address, unsigned int size) {
char* data = new char[size];
for(int i=0; i < size; i++){
vm_readv(reinterpret_cast<void*>(address + (sizeof(char)*i)), reinterpret_cast<void*>(data + i), sizeof(char));
if(data[i] == '\0'){
break;
}
}
return data;
}
I'm not sure how to fix it.我不知道如何解决它。
I've tried to add delete[] data;
我尝试添加
delete[] data;
before break;
break;
and it stops the memory, the program also runs.它停止 memory,程序也运行。 But i think this may crash the program somewhere after??
但我认为这可能会在某处使程序崩溃??
At any rate, I'm confused on how to properly deal with the leak.无论如何,我对如何正确处理泄漏感到困惑。
I've been reading and using a smart pointer might be a good way to resolve it, but again, I don't know how to properly turn char* data = new char[size];
我一直在阅读和使用智能指针可能是解决它的好方法,但同样,我不知道如何正确打开
char* data = new char[size];
into a pointer without breaking data[i]
.在不破坏
data[i]
的情况下放入指针。
Edit: Attempts on stopping the leak, the leak stop with this.编辑:尝试停止泄漏,泄漏由此停止。 But I think it may cause a crash later?
但我认为它可能会导致以后崩溃?
char* ReadString(u_int address, unsigned int size) {
char* data = new char[size];
for(int i=0; i < size; i++){
vm_readv(reinterpret_cast<void*>(address + (sizeof(char)*i)), reinterpret_cast<void*>(data + i), sizeof(char));
if(data[i] == '\0'){
delete [] data; // ------->>>>>>> Here
break;
}
}
return data;
}
Don't use raw new
and delete
.不要使用原始
new
和delete
。 It was never good practice to use new
whenever you need to create an object in C++.每当您需要在 C++ 中创建 object 时,使用
new
从来都不是好的做法。 If you need a string then use std::string
.如果您需要一个字符串,请使用
std::string
。 It's resize method lets you resize it and some_string[i]
lets you access the i-th character.它的 resize 方法可让您调整其大小,而
some_string[i]
可让您访问第 i 个字符。 I assume vm_readv
reads a single character, though I am a bit confused by the usage of void*
and reinterpret_cast
.我假设
vm_readv
读取单个字符,尽管我对void*
和reinterpret_cast
的使用有点困惑。
std::string ReadString(u_int address, unsigned int size) {
std::string result;
result.resize(size);
for (size_t i=0;i<size;++i) {
// read result[i]
// its address is &result[i]
}
return result;
}
In your code the leak is not in the function but in the caller of the function.在您的代码中,泄漏不在 function 中,而是在 function 的调用者中。 Because the function returns
data
it transfers ownership of it (= responsibility to delete it) to the caller.因为 function 返回
data
,它将所有权(=删除它的责任)转移给调用者。 Not using manual memory allocations is simpler, less error prone and if you need a string of dynamic size the problem of managing the memory has already been solved for you: std::string
.不使用手动 memory 分配更简单,更不容易出错,如果您需要动态大小的字符串,管理 memory 的问题已经为您解决:
std::string
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.