From 119f1e8f72908fdc2ab5a828900e6757fa96b141 Mon Sep 17 00:00:00 2001 From: taynpg Date: Wed, 9 Apr 2025 09:14:30 +0800 Subject: [PATCH] =?UTF-8?q?fix=EF=BC=9A=E4=BF=AE=E6=AD=A3=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E5=86=85=E5=AD=98=E6=B3=84=E6=BC=8F=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- client/client.cpp | 11 +++++++++++ client/client.h | 1 + util/util.cpp | 9 ++++++++- 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/client/client.cpp b/client/client.cpp index 7574ea2..2d8f338 100644 --- a/client/client.cpp +++ b/client/client.cpp @@ -122,6 +122,15 @@ void CClient::print_help(bool detail) TLOGI("{}", sp); } +void CClient::free_buf_manual(CFrameBuffer* buf) +{ + if (buf == nullptr) { + return; + } + delete buf->data_; + buf->data_ = nullptr; +} + void CClient::run(const std::string& ip, const std::string& port, const std::string& config_dir) { fs::path fp(config_dir); @@ -1331,6 +1340,8 @@ void CClient::send_file_data_th(const char* keys) TLOGE("Stop Trans {} To {} failed.", t->cur_file_, str_key); return; } + + free_buf_manual(buf.get()); buf->type_ = TYPE_TRANS_FILE; buf->mark_ = 1; diff --git a/client/client.h b/client/client.h index 31f4609..e50fab2 100644 --- a/client/client.h +++ b/client/client.h @@ -71,6 +71,7 @@ private: std::string read_uuid(); void get_id(); void print_help(bool detail); + void free_buf_manual(CFrameBuffer* buf); private: void handle_frame(CFrameBuffer* buf); diff --git a/util/util.cpp b/util/util.cpp index 93ce139..3633732 100644 --- a/util/util.cpp +++ b/util/util.cpp @@ -142,7 +142,14 @@ void serialize(CMessageInfo& msg_info, char** out_buf, int& len) // 计算总长度 len = sizeof(int) * 4 + info.id.size() + info.uuid.size() + info.str.size() + info.data.size() + kz; - *out_buf = new char[len]{}; // 分配内存(调用方负责释放) + + // 《这里为了效率》,认为如果 *out_buf 不为空,则直接使用,且长度符合要求 + // 调用方负责确保内存一致性和可用性。 + // 即,如果调用方及高频率调用 serialize, 且每次 len 固定就复用内存,完了再释放。 + // 低频率或者 len 不固定时,每次都释放内存,并置 nullptr。 + if (*out_buf == nullptr) { + *out_buf = new char[len] {}; // 分配内存(调用方负责释放) + } char* ptr = *out_buf + kz;