Skip to content

Commit 7555cfe

Browse files
authored
fix inference double free bug (#12613)
1 parent 5dc57b7 commit 7555cfe

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

paddle/fluid/inference/api/api.cc

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
See the License for the specific language governing permissions and
1313
limitations under the License. */
1414

15+
#include <glog/logging.h>
1516
#include "paddle/fluid/inference/api/paddle_inference_api.h"
1617

1718
namespace paddle {
@@ -40,19 +41,36 @@ PaddleBuf::PaddleBuf(PaddleBuf&& other)
4041
PaddleBuf::PaddleBuf(const PaddleBuf& other) { *this = other; }
4142

4243
PaddleBuf& PaddleBuf::operator=(const PaddleBuf& other) {
44+
if (!other.memory_owned_) {
45+
data_ = other.data_;
46+
length_ = other.length_;
47+
memory_owned_ = other.memory_owned_;
48+
} else {
49+
Resize(other.length());
50+
memcpy(data_, other.data(), other.length());
51+
length_ = other.length();
52+
memory_owned_ = true;
53+
}
54+
return *this;
55+
}
56+
57+
PaddleBuf& PaddleBuf::operator=(PaddleBuf&& other) {
4358
// only the buffer with external memory can be copied
44-
assert(!other.memory_owned_);
4559
data_ = other.data_;
4660
length_ = other.length_;
4761
memory_owned_ = other.memory_owned_;
62+
other.data_ = nullptr;
63+
other.length_ = 0;
64+
other.memory_owned_ = false;
4865
return *this;
4966
}
5067

5168
void PaddleBuf::Resize(size_t length) {
5269
// Only the owned memory can be reset, the external memory can't be changed.
5370
if (length_ == length) return;
54-
assert(memory_owned_);
55-
Free();
71+
if (memory_owned_) {
72+
Free();
73+
}
5674
data_ = new char[length];
5775
length_ = length;
5876
memory_owned_ = true;
@@ -68,7 +86,7 @@ void PaddleBuf::Reset(void* data, size_t length) {
6886
void PaddleBuf::Free() {
6987
if (memory_owned_ && data_) {
7088
assert(length_ > 0);
71-
delete static_cast<char*>(data_);
89+
delete[] static_cast<char*>(data_);
7290
data_ = nullptr;
7391
length_ = 0;
7492
}

paddle/fluid/inference/api/paddle_inference_api.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,12 @@ class PaddleBuf {
4040
// Copy only available when memory is managed externally.
4141
explicit PaddleBuf(const PaddleBuf&);
4242
PaddleBuf& operator=(const PaddleBuf&);
43+
PaddleBuf& operator=(PaddleBuf&&);
4344
// Do not own the memory.
4445
PaddleBuf(void* data, size_t length)
4546
: data_(data), length_(length), memory_owned_{false} {}
4647
// Own memory.
47-
explicit PaddleBuf(size_t length)
48+
PaddleBuf(size_t length)
4849
: data_(new char[length]), length_(length), memory_owned_(true) {}
4950
// Resize to `length` bytes.
5051
void Resize(size_t length);

0 commit comments

Comments
 (0)