0%

c_autoclean

实现C语言的自动清理功能

GCC的变量attribute支持cleanup属性,定义如下:

1
2
3
4
5
6
7
8
9
10
11
cleanup (cleanup_function)
The cleanup attribute runs a function when the variable goes out of scope.
This attribute can only be applied to auto function scope variables; it may not
be applied to parameters or variables with static storage duration. The function
must take one parameter, a pointer to a type compatible with the variable. The
return value of the function (if any) is ignored.
If ‘-fexceptions’ is enabled, then cleanup function is run during the stack
unwinding that happens during the processing of the exception. Note that the
cleanup attribute does not allow the exception to be caught, only to perform
an action. It is undefined what happens if cleanup function does not return
normally.

如果变量设置了cleanup属性,那么在变量离开它所属作用域时会自动调用配置的cleanup函数。那么,可以通过设置变量的cleanup属性,自动回收变量相关的内存、关闭句柄以及释放锁。

基本用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void defer_func(char **p)
{
printf("this is defer, free: %s\n", *p);
free(*p);
*p = NULL;
}

int main()
{
__attribute__ ((__cleanup__(defer_func))) char *c = NULL;
__attribute__ ((__cleanup__(defer_func))) char *b = NULL;
__attribute__ ((__cleanup__(defer_func))) char *a = NULL;

a = strdup("a");
b = strdup("b");
c = strdup("c");
return 0;
}