don*_*lan 1 c++ memory-management c-strings
假设我执行以下操作:
char *get_data(...) {
char *c_style = (char *) malloc(length * sizeof(char));
load_c_string_with_my_c_function(c_style, length, input);
return c_style;
}
int main() {
std::string data(get_data(...));
// free(data.c_str()); ?? -- are the malloc'd bytes now managed?
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法释放get_data()分配的内存?评论free(data.c_str());工作会吗?
一旦你这样做了
std::string data(get_data(...));
Run Code Online (Sandbox Code Playgroud)
没有办法让get_data()返回的指针返回,所以你会泄漏那个内存.要解决这个问题,首先要get_data()返回a std::string,这样你根本不用担心内存管理问题.那会给你
std::string get_data(...) {
std::string data(length, '\0');
load_c_string_with_my_c_function(data.data(), length, input); // requires C++17
// load_c_string_with_my_c_function(&data[0], length, input); // use this for pre-C++17 compilers
return data;
}
Run Code Online (Sandbox Code Playgroud)
现在没有内存泄漏.如果你不能这样做,那么你需要捕获指针,用它来初始化字符串,然后释放指针
char* ret = get_data(...);
std::string data(ret);
free(ret);
Run Code Online (Sandbox Code Playgroud)