c++ - 如何释放 Protocol Buffer 内存

标签 c++ memory memory-leaks protocol-buffers

message LongUserIdSeqIdMapData {
map<int64, int32> userid_seqid = 1;
map<int32, int64> sedid_userid = 2; }

void GetUserIdSeqId(const std::string &user_id_seq_id_file) {
std::ifstream infile(user_id_seq_id_file);
infile.seekg(0, infile.end);
size_t length = infile.tellg();
infile.seekg(0, infile.beg);
auto *buffer = new char[length];
infile.read(buffer, length);
auto long_user_id_seq_id_map = new com::jaymz::poseidon::LongUserIdSeqIdMapData::LongUserIdSeqIdMapData();
if (!(*long_user_id_seq_id_map).ParseFromArray(buffer, length)) {
    std::cout << "Parse user_id_seq_id_file Fail, Please Check Your File!" << std::endl;
} else {
    std::cout << "Parse user_id_seq_id_file Success" << std::endl;
}
delete[] buffer;
delete long_user_id_seq_id_map;

}

我先将LongUserIdSeqIdMapData数据写入文件,然后通过调用函数GetUserIdSeqId从文件中解析它,我发现程序在执行GetUserIdSeqId时占用了190M物理内存,但是执行完GetUserIdSeqId后,程序仍然占用190M物理内存,因为没有内存被释放,我不知道为什么。

最佳答案

C++中有一个释放内存的函数:

google::protobuf::ShutdownProtobufLibrary();

https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.common#ShutdownProtobufLibrary.details

Shut down the entire protocol buffers library, deleting all static-duration objects allocated by the library or by generated .pb.cc files.

There are two reasons you might want to call this:

  • You use a draconian definition of "memory leak" in which you expect every single malloc() to have a corresponding free(), even for objects which live until program exit.
  • You are writing a dynamically-loaded library which needs to clean up after itself when the library is unloaded.

It is safe to call this multiple times. However, it is not safe to use any other part of the protocol buffers library after ShutdownProtobufLibrary() has been called.

这应该可以解决您的问题!

关于c++ - 如何释放 Protocol Buffer 内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50414346/

相关文章:

ios - 不在 Xamarin 的 UIViewController 上调用 dealloc

c# - 删除 UWP 中的导航缓存

c++ - Boost::serialization 和 boost::mpi 通过基类指针广播派生类

c++ - 如何在没有root权限的情况下获取linux中进程的内存使用情况

c++ - 如何在类成员函数内部的printf中获取编译警告

c++ - std::bind、this 和 QtConcurrent

memory - VHDL - 如何优雅地初始化 std_logic_vector 数组?

java - 测量代码单元的内存使用情况

android - 按下后退按钮时释放 Android 上的内存

java - 如何摆脱“Activity 已泄漏服务连接”错误