使用 RAII 机制规避内存泄漏风险
使用 RAII 机制规避内存泄漏风险
在 c++ 开发过程中,有时候需要使用到一些 c 语言的接口,比如 malloc/free,这些接口在内存管理上存在一定的风险,容易导致内存泄漏。本文介绍一种使用 RAII 机制规避内存泄漏风险的方法。
改良前
下面这个代码存在一个问题,在 use_data 函数中,如果函数提前返回,则 drop_data 函数不会执行,会导致内存泄漏。在 c 语言中,有两个办法可以解决这个问题,一个是使用 goto 语句, 跳到指定地方去调用 drop_data 再返回, 或者在每一个判断条件里返回之前都调用一下 drop_data 来释放内存。但是这两种办法都不优雅,而且容易出错。我们将介绍一种使用 RAII 的方式来解决这个问题。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/// 代码仅仅用于演示,没有实际意义
#include <iostream>
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <unistd.h>
#define CHECK_TRUE(condition, ret_value) \
do { \
if (!(condition)) { \
return ret_value; \
} \
} while (0)
struct Data {
void *buffer;
uint16_t size;
};
void make_data(const char *raw_data, struct Data *data) {
if (!data) {
return;
}
uint32_t size = strlen(raw_data);
data->buffer = malloc(size + 1);
if (!data->buffer) {
return;
}
memcpy(data->buffer, raw_data, size);
((char *)data->buffer)[size] = '0';
}
auto extract_data(struct Data *data) -> std::string {
if (!data) {
return "invalid";
}
if (!data->buffer) {
return "unknown";
}
return std::string((char *)data->buffer);
}
void drop_data(struct Data *data) {
if (!data) {
return;
}
if (!data->buffer) {
return;
}
free(data->buffer);
data->buffer = nullptr;
}
int use_data() {
Data data;
const char *raw_data = "GuangDong\0";
make_data(raw_data, &data);
auto str = extract_data(&data);
CHECK_TRUE(str == "GuangDong", 4);
CHECK_TRUE(str == "SiChuan", 3);
CHECK_TRUE(str == "YunNan", 2);
CHECK_TRUE(str == "GuiZhou", 1);
CHECK_TRUE(str == "invalid", -1);
CHECK_TRUE(str == "unknown", -2);
drop_data(&data);
return 0;
}
int main() {
while (1) {
std::cout << use_data() << "\n";
sleep(1);
}
return 0;
}
改良后
将要调用的函数放入类的析构函数里,当函数生命周期结束时会先调用 drop_data 来释放内存。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/// 代码仅仅用于演示,没有实际意义
#include <iostream>
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <unistd.h>
#include <functional>
#define CHECK_TRUE(condition, ret_value) \
do { \
if (!(condition)) { \
return ret_value; \
} \
} while (0)
struct Data {
void *buffer;
uint16_t size;
};
class ScopeAutoCall {
public:
explicit ScopeAutoCall(const std::function<void(void)> &callback)
: callback_(callback) {}
~ScopeAutoCall() {
callback_();
}
ScopeAutoCall(const ScopeAutoCall &) = delete;
ScopeAutoCall &operator=(const ScopeAutoCall &) = delete;
private:
std::function<void(void)> callback_;
};
void make_data(const char *raw_data, struct Data *data) {
if (!data) {
return;
}
uint32_t size = strlen(raw_data);
data->buffer = malloc(size + 1);
if (!data->buffer) {
return;
}
memcpy(data->buffer, raw_data, size);
((char *)data->buffer)[size] = '0';
}
auto extract_data(struct Data *data) -> std::string {
if (!data) {
return "invalid";
}
if (!data->buffer) {
return "unknown";
}
return std::string((char *)data->buffer);
}
void drop_data(struct Data *data) {
if (!data) {
return;
}
if (!data->buffer) {
return;
}
free(data->buffer);
data->buffer = nullptr;
}
int use_data() {
Data data;
const char *raw_data = "GuangDong\0";
make_data(raw_data, &data);
auto str = extract_data(&data);
ScopeAutoCall sac([&]() { drop_data(&data); });
CHECK_TRUE(str == "GuangDong", 4);
CHECK_TRUE(str == "SiChuan", 3);
CHECK_TRUE(str == "YunNan", 2);
CHECK_TRUE(str == "GuiZhou", 1);
CHECK_TRUE(str == "invalid", -1);
CHECK_TRUE(str == "unknown", -2);
return 0;
}
int main() {
while (1) {
std::cout << use_data() << "\n";
sleep(1);
}
return 0;
}
本文由作者按照 CC BY 4.0 进行授权