I'm very new to C++ and is trying to compile a program, however it's leaking memory and this part of the code.
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;
before break;
and it stops the memory, the program also runs. 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];
into a pointer without breaking 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
. It was never good practice to use new
whenever you need to create an object in C++. If you need a string then use std::string
. It's resize method lets you resize it and some_string[i]
lets you access the i-th character. I assume vm_readv
reads a single character, though I am a bit confused by the usage of void*
and 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. Because the function returns data
it transfers ownership of it (= responsibility to delete it) to the caller. 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.